let md5 = require("../../utils/md5.js")
let axios = require("../../utils/util.js")
const {
  Parser,
  Player
} = require("../../utils/svgaplayer.weapp")
// 声明变量
import {
  Room_cache_image,
} from '../../utils/cache_image';
import {
  initSDK,
  authCheck,
  startPush,
  IMSDK,
  stopPlayAll
} from '../../utils/common';
const app = getApp()
let zg;
Page({
  data: {
    page_mylog_data: true, //是否还有数据
    page_mylog: 0, //获奖记录页码
    points: [], //连送数组
    loading: true, //进入房间加载中
    image_filepath: 'https://xunyinjiaoyou.oss-cn-qingdao.aliyuncs.com/static/images/yutu2.svga', //缓存进场特效 
    svga5_state: true, //true可以播放当前没有队列，false当前队列正在执行
    play_svge5: [], //进场特效
    timer_scokent: null,
    lockReconnect: false, //webscokent重启状态
    voide_mp4: "", //礼物视频地址
    page_loading: false, //加载中
    page_show: false, //没有更多
    display: 'none', //block
    Currentlimit: 0,
    instructions: {}, //玩法说明
    nameList_page: [], //namelist
    ListRestriction: false, //能量池中奖名单
    countDown: 3,
    energyOpenNormal: {}, //普通能量池中奖
    EnergyEating: false, //能量池显示true
    EnergyPoolLevel: 1, //1普通能量池2普通中奖3高能量池4高中奖 
    xinyuanluopan: false, //心愿罗盘 
    inputUp: true, //键盘上移
    isFocus: false,
    iptValue: "",
    room_password: false, //房间密码
    luckGiftUrl: [], //幸运礼物
    isMp4_video: false, //播放视频
    fullScreen: false,
    user_count: "", //在线人数
    my_info: {}, //房间个人排名
    maixu_image: '', //静帧图片
    maixu: false, //随机抽奖
    number: '', //随机麦序
    // recordList: ['1','2','3'],
    startX: 0, //开始坐标
    startY: 0,
    Sum_: 0, //未读信息
    issend_: false,
    receiversArr: [], //接收礼物人信息
    // position_left:0,
    position_width: 100, //礼物特效
    position_height: 100, //礼物特效
    webview: '', //跳转页面
    iswebview: false,
    luckBox: [], //幸运礼物
    ArrList: [], //消息队列
    gift_imgicon_wu: '', //送完的礼物，没有特效
    issvag_bomb: false, //爆炸特效第二次加载
    process: false, //签名是否有礼物
    svgaArr: [], //svga图片队列
    temporary: [], //临时进场人
    joinRoom_s: false, //别人进场动画
    luckbox_: false, //幸运礼物
    list_userlist: [],
    position_bao: '', //抱人上麦位
    page: 1,
    onlineList: "",
    input_keyboardentry: 0, //键盘高度
    isinput_keyboardentry: false,
    request: false,
    pullFlow: true, //开启声音状态
    microPhone_: true, //麦克风声音大小
    iscamera: false, //关闭摄像头
    // channel_name: '', //房间
    disable: false, //全麦禁止点击
    big_gift_: {}, //大礼物特效
    isbig_gift: false,
    isupgrade: false, //升级效果
    upgrade: {}, //升级效果
    isWholeWheat: false, //是否显示全麦礼物
    WholeWheat: {}, //全服礼物信息
    is_new_infor: false, //有新信息
    chat_barrage: {}, //公屏礼物
    list_image_gb_one: '', //背景图
    turn: '', //抽奖1连10连
    enter_info: '', //进场特效
    driver_info: '', //进场动画
    // tim: {},
    pusherVideoContext: null,
    features: false, //更多功能
    roomOnline: false, //在线用户
    roomOnlineRoom_list: false, //房间榜单
    chatFullInfo: {}, //房间全部信息
    businessCard: false, //房间信息是否显示
    approachAnimation: false, //进场动画
    selext_model: false, //收礼物model
    giftInfo: {}, //送礼物显示人对象礼物
    is_one: '1', //1为奖池，2获取小魔方
    roomUserList: [],
    lottery_num: 0, //剩余抽奖次数
    svga_isshow: false,
    opengift: [], //十连抽中奖
    body_index: '1', //1魔方,2规则,3获奖记录,4抽奖结果
    zogtoken: null,
    zego_token_new_: null, //token鉴权
    microPhone: false, //上麦麦克风
    img_level: "http://img.xunyinjiaoyou.com/static/level3/",
    img_charm: "http://img.xunyinjiaoyou.com/static/charm3/",
    img_header: "https://xunyinjiaoyou.oss-cn-qingdao.aliyuncs.com/",
    list: {}, //房间内麦信息
    roomId: "", //房间id
    // siteList: 9, //麦序列表
    rankList: 3, //排行榜列表
    top_list: "", //富豪榜前三名
    // room_userlist:"",//麦序列表
    nickname: "", //弹出窗麦消息
    introduceShow: false, //玩法介绍是否显示
    cardShow: false, //个人卡片是否显示
    // chatText: "", //消息文本
    luckShow: false, //抽奖是否显示
    luckNum: 0, //抽奖显示页
    diamond: "", //钻石数
    user_Info_list: {}, //个人信息
    drawNum: 1, //单抽/多抽
    luckrankList: [], //手气榜列表
    jackpotList: [], //奖池列表
    giftList: [], //抽奖礼物列表 
    giftShow: false, //送礼物是否显示
    daygiftList: [], //日常礼物
    baggiftList: [], //背包礼物
    luckgiftList: [], //幸运礼物
    showgiftList1: [], //显示礼物1
    showgiftList2: [], //显示礼物2
    showgiftList3: [], ////显示礼物3
    showgiftList4: [], //显示礼物4
    // showgiftNum0: 0, //显示送礼物人
    showgiftNum1: 0, //显示礼物下标1
    showgiftNum2: 8, //显示礼物下标2
    sendgiftNum: 0, //礼物类型
    DescriptionIntroduction: false, //能量池规则
    sendNumList: [{
        num: '1',
        title: '一心一意'
      },
      {
        num: '6',
        title: '溜'
      },
      {
        num: '21',
        title: '只爱你'
      },
      {
        num: '52',
        title: '我爱你'
      },
      {
        num: '99',
        title: '长长久久'
      },
      {
        num: '288',
        title: '要抱抱'
      },
      {
        num: '521',
        title: '我爱你'
      },
      {
        num: '1314',
        title: '一生一世'
      }
    ], //礼物赠送数量列表
    sendNum: 1, //赠送礼物数量
    gift_id: "", //赠送礼物id
    sendNumShow: false, //赠送礼物数量是否显示
    sendpersonList: [0, 1, 2, 3, 4, 5, 6, 7, 8], //送礼物人选列表   
    userlist_: [], //本地存储麦上用户id
    user_list: [], //显示送礼物人
    changegift_userlist: 0, //全麦送礼物
    gift_userid: [], //收礼物人
    isown: false, //点击麦位是否是本人
    isadministrators: false, //是否管理员
    isguan: false, //管理员点击
    memberId: '', //点击麦序获取的用户user_id
    gift_imgicon: '', //送礼物图标
    message: {}, //IM通信信息
    inputMessage_: '聊点什么吧...', //发送消息
    inputMessage: '',
    messageList: [], //消息合集
    messageList_liaot: [], //聊天消息合集
    messageList_: [], //表情包
    expression: false, //表情包合集是否显示
    expressionEnsemble: [], //表情包素材
    connectType: -1, // -1为初始状态，1为连接，0断开连接
    streamList: [], //回调流状态
    position_mk: null, //说话人位置
    imageFile: null, //svg
    giftMoney: '', //礼物价值
    giftName: "", //礼物名字
    gift_nowar: false, //送礼图片
    gift_nowar_: false, //送礼图片
    specialEffects: false, //fasle为开启特效，true关闭
    jurisdiction: [{
        fun_name: "移除麦序"
      },

      // {
      //   fun_name:"设为管理"
      // },
      {
        fun_name: "设为禁言"
      },
      {
        fun_name: "清空魅力值"
      },
      {
        fun_name: "踢出房间"
      },
    ],
    background: ["red", "pink", "yellowgreen"],
    box_rule: false, //魔盒规则三行
    ad_list: [], //轮播图
    indicatorDots: true,
    vertical: false,
    autoplay: true,
    interval: 2000,
    duration: 500,
    circular: true,
    scrollTop: '', //消息自动滚屏
    po_emo_top: '', //追踪发消息人位置
    po_emo_left: '',
    isemoticon: null, //表情包
    canShow: -1,
    systemobj: "", //系统消息/互动消息
    livePusherUrl: '', // 推流地址
    livePusher: null, // live-pusher 的 Context，内部只有一个对象
    livePlayerList: [],
    svgaHeight: "",
    svgaWidth: "",
    NextBox: false, //魔盒
    is_close: true, //关闭还是返回
    text_title_list: '', //规则文本
    lucktop: [], //手气榜
    isJackpot: false, //底部奖池
    number_s: null, //购买次数
    InformationChat: false, //聊天对话

    type: 1, //0财富1魅力
    dateType: 1, //1日榜2周榜
    rankList1: "",
    rankList2: "",
    animationMain: null, //正面
    animationBack: null, //背面
    animationMain_: null, //正面
    animationBack_: null, //背面
    energy_index: {
      percentage: 0,
    }, //能量池首页
  },
  showEragy() {
    // this.setData({
    //   EnergyEating: true,
    //   display: "block"
    // })
    // this.energy()
  },
  hideview: function () {
    this.setData({
      EnergyEating: false,
      display: "none"
    })
  },
  joinPlay(data) {
    // console.log(data.currentTarget.dataset.num);
    let EnergyPoolLevel;
    if (this.data.EnergyPoolLevel > 2) {
      EnergyPoolLevel = 2
    } else {
      EnergyPoolLevel = 1
    }
    let params = {
      num: data.currentTarget.dataset.num,
      type: EnergyPoolLevel
    };
    axios.axios({
      url: "/energy/joinPlay",
      data: params
    }).then((res) => {
      if (res.data.status == 0) {
        this.setData({
          "energy_index.diamond": res.data.result.diamond,
          "energy_index.myNum": res.data.result.myNum,
        })
      } else {
        wx.showToast({
          title: res.data.text,
          icon: 'none',
          duration: 2000 //持续的时间
        })
      }
    })
  },
  // 能量池首页
  energy() {
    let EnergyPoolLevel;
    if (this.data.EnergyPoolLevel > 2) {
      EnergyPoolLevel = 2
    } else {
      EnergyPoolLevel = 1
    }
    let params = {
      type: EnergyPoolLevel
    };
    axios.axios({
      url: "/energy/index",
      data: params
    }).then((res) => {
      if (res.data.status == 0) {
        this.setData({
          energy_index: res.data.result,
          EnergyPoolLevel: res.data.result.type == '1' ? '1' : '3',
        })
      } else {
        wx.showToast({
          title: res.data.text,
          icon: 'none',
          duration: 2000 //持续的时间
        })
      }
    })
  },
  tab_qiehuang(data) {
    if (data) {
      this.setData({
        EnergyPoolLevel: data.currentTarget.dataset.pool
      })
    }
    this.energy()
  },
  cloase_wishCompass() {
    this.setData({
      xinyuanluopan: false,
    })
  },
  setValue: function (e) {
    var that = this;
    that.setData({
      iptValue: e.detail.value
    });
    if (that.data.iptValue.length == '6') {
      this.setData({
        password: this.data.iptValue,
      })
      this.joinRoom()
      // console.log("6位密码");
    }
  },

  //他人礼物,魔方抽奖
  async playSvga4(svgaUrl, IDclassname, loops) {
    console.log("礼物,魔方抽奖", svgaUrl, IDclassname, loops);
    if (this.data.specialEffects) {
      return
    }
    if (this.data.process) {
      return
    }
    try {
      let that = this
      that.setData({
        process: true,
      })
      const parser = new Parser();
      const player = new Player;
      player.loops = loops;

      await player.setCanvas(IDclassname)
      const videoItem = await parser.load(svgaUrl);
      await player.setVideoItem(videoItem);
      player.startAnimation();
      player.onFinished(res => {
        console.log("动画停止了")
        that.setData({
          process: false,
          approachAnimation: false, //进场特效
        })
        if (that.data.turn == '1') {
          that.setData({
            body_index: '4',
            turn: '',
          })
        } else if (that.data.turn == '10') {
          that.setData({
            body_index: '5',
            turn: '',
          })
        }
      })
    } catch (error) {
      this.setData({
        process: false,
        approachAnimation: false, //进场特效
      })
    }
  },
  closeVideo() {
    console.log("视频结束-------------------------------------------------------------");
    this.setData({
      isMp4_video: false,
      luckbox_: false,
    })
    this.playSvga8(this.data.luckGiftUrl[0], "#myCanvas6", '1')
  },
  //幸运礼物队列
  async playSvga8(svgaUrl) {
    let that = this;
    if (this.data.specialEffects) { //关闭特效
      return
    }
    try {
      let codesvga = RegExp(/.svga/);
      if (codesvga.test(svgaUrl.result.giftInfo.imageFile)) {
        this.playSvga9(svgaUrl.result.giftInfo.imageFile)
      } else {
        console.log(svgaUrl);
        that.setData({
          giftInfo: svgaUrl.result,
          receiversArr: svgaUrl.result.receivers,
          gift_imgicon_wu: svgaUrl.result.giftInfo.icon,
          gift_nowar_: true, //送礼图片
          gift_nowar: true,
        })
        let timer
        clearTimeout(timer)
        timer = setTimeout(() => { //设置延迟执行
          svgaUrl.result.receivers.forEach(item => {
            if (item.position == 0) {
              item.position_top = -30
              item.position_left = 4
            } else if (item.position < 5) {
              item.position_top = -16
              item.position_left = item.position * 24 - 56
            } else {
              item.position_top = -4
              item.position_left = (item.position - 4) * 24 - 56
            }
          })
          this.setData({
            receiversArr: svgaUrl.result.receivers,
            position_width: 30,
            position_height: 30,
          })
        }, 1000);
        let timers
        clearTimeout(timers)
        timers = setTimeout(() => { //设置延迟执行
          that.setData({
            position_width: 100,
            position_height: 100,
            gift_imgicon_wu: '',
            gift_nowar_: false, //送礼图片
          })
          this.data.luckGiftUrl.shift()
          if (that.data.luckGiftUrl.length > 0) {
            that.setData({
              isMp4_video: true,
            })
          } else {
            that.close_myCanvas3()
          }
        }, 4000);
      }
    } catch (error) {

    }
  },
  async playSvga9(svgaUrl) {
    const parser = new Parser();
    const player = new Player;
    player.loops = '1'
    await player.setCanvas("#myCanvas6")
    const videoItem = await parser.load(svgaUrl);
    await player.setVideoItem(videoItem);
    player.startAnimation();
    player.onFinished(res => {
      console.log("动画停止了")
      this.data.luckGiftUrl.shift()
      this.setData({
        luckbox_: false,
        approachAnimation: true
      })
      if (this.data.luckGiftUrl.length > 0) {
        this.setData({
          isMp4_video: true,
        })
      } else {
        this.setData({
          approachAnimation: false,
        })
      }
    })
  },
  rotateFn(e) {
    var id = e.currentTarget.dataset.id
    this.animation_main = wx.createAnimation({
      duration: 400,
      timingFunction: 'linear'
    })
    this.animation_back = wx.createAnimation({
      duration: 400,
      timingFunction: 'linear'
    })
    if (id == 1) {
      this.animation_main.rotateY(180).step()
      this.animation_back.rotateY(0).step()
      this.setData({
        animationMain: this.animation_main.export(),
        animationBack: this.animation_back.export(),
      })
    } else {
      this.animation_main.rotateY(0).step()
      this.animation_back.rotateY(-180).step()
      this.setData({
        animationMain: this.animation_main.export(),
        animationBack: this.animation_back.export(),
      })
    }
  },
  rotateFn_(e) {
    var id = e.currentTarget.dataset.id
    this.animation_main_ = wx.createAnimation({
      duration: 400,
      timingFunction: 'linear'
    })
    this.animation_back_ = wx.createAnimation({
      duration: 400,
      timingFunction: 'linear'
    })
    // 点击正面
    if (id == 3) {
      this.animation_main_.rotateY(180).step()
      this.animation_back_.rotateY(0).step()
      this.setData({
        animationMain_: this.animation_main_.export(),
        animationBack_: this.animation_back_.export(),
      })
    } else {
      this.animation_main_.rotateY(0).step()
      this.animation_back_.rotateY(-180).step()
      this.setData({
        animationMain_: this.animation_main_.export(),
        animationBack_: this.animation_back_.export(),
      })
    }
  },
  //聊天对话框
  InformationChat() {
    this.setData({
      InformationChat: true
    })
  },
  //互动消息
  tointeractMes() {
    wx.navigateTo({
      url: '/pages/systemInformation/systemInformation'
    })
  },
  shez_xians() {
    this.setData({
      DescriptionIntroduction: !this.data.DescriptionIntroduction
    })
  },
  nameList(data) {
    let luck = data.currentTarget.dataset.luck
    this.setData({
      Currentlimit: luck,
      nameList_page: [],
    })
    this.luckToppage()
  },
  // 名单
  luckToppage() {
    this.setData({
      page_loading: true
    })
    let params = {
      page: this.data.page,
      type: this.data.EnergyPoolLevel < 3 ? '1' : '2',
      userId: app.globalData.user_id,
      token: app.globalData.userToken,
    };
    axios.axios({
      url: "/energy/luckTop",
      data: params
    }).then((res) => {
      if (res.data.status == 0) {
        this.setData({
          DescriptionIntroduction: false,
          ListRestriction: true,
        })
        if (res.data.result.length == '20') {
          let a = this.data.nameList_page;
          let b = res.data.result
          let c = a.concat(b);
          this.setData({
            nameList_page: c,
          })
        } else {
          let a = this.data.nameList_page;
          let b = res.data.result
          let c = a.concat(b);
          this.setData({
            page_show: true,
            nameList_page: c,
          })
        }
      }
      this.setData({
        page_loading: false
      })
    })
  },
  PlayInstructions(data) {
    let luck = data.currentTarget.dataset.luck
    let params = {
      type: this.data.EnergyPoolLevel < 3 ? '1' : '2',
      userId: app.globalData.user_id,
      token: app.globalData.userToken,
    };
    axios.axios({
      url: "/energy/about",
      data: params
    }).then((res) => {
      if (res.data.status == 0) {
        this.setData({
          Currentlimit: luck,
          DescriptionIntroduction: false,
          ListRestriction: true,
          instructions: res.data.result
        })
      }
    })
  },
  ListRestriction2() {
    this.setData({
      ListRestriction: false
    })
  },

  // live-pusher 绑定推流事件
  onPushStateChange(e) {
    // 透传推流事件给 SDK
    zg.updatePlayerState(app.globalData.user_id, e, 1);
  },

  //获取参数
  giv_info() {
    let params = {
      userId: app.globalData.user_id,
      token: app.globalData.userToken,
    };
    axios.axios({
      url: "/message/syslist",
      data: params
    }).then((res) => {
      // console.log(res.data.result)
      // var sum = Number(res.data.result.sysCountUnread) + Number(res.data.result.callCountUnread);
      this.setData({
        systemobj: res.data.result,
        // ishongdian: sum
      })
    })
  },
  //聊天对话框
  InformationChat2() {
    this.setData({
      InformationChat: false
    })
  },
  //房间管理
  AdministrationRoom() {
    console.log('房间管理');
    return wx.showToast({
      title: "管理员功能请前往app体验",
      icon: 'none',
      duration: 2000 //持续的时间
    })
  },
  //房间上锁
  roomLock() {
    console.log('房间上锁');
    return wx.showToast({
      title: "管理员功能请前往app体验",
      icon: 'none',
      duration: 2000 //持续的时间
    })
  },
  //清空魅力值
  clearCharm_guanli() {
    console.log('清空魅力值');
    let timestamp = (Date.parse(new Date()) / 1000).toString();
    let arys = {
      roomId: this.data.roomId,
      userId: app.globalData.user_id,
      toUserId: '0',
      token: app.globalData.userToken,
      time: timestamp,
    };
    let _token = axios.encryption(arys);
    let params = {
      roomId: this.data.roomId,
      userId: app.globalData.user_id,
      toUserId: '0',
      token: app.globalData.userToken,
      time: timestamp,
      sign: md5.hexMD5(_token),
    };
    axios.axios({
      url: "/chat/clear_charm",
      data: params
    }).then((res) => {
      wx.showToast({
        title: res.data.text,
        icon: 'none',
        duration: 2000 //持续的时间
      })
    })
  },
  //关闭特效
  turnoffspecialEffects() {
    if (wx.getStorageSync('specialEffects') != '') {
      if (wx.getStorageSync('specialEffects') == true) {
        wx.setStorageSync('specialEffects', false);
      } else {
        wx.setStorageSync('specialEffects', true);
      }
    } else {
      wx.setStorageSync('specialEffects', true);
    }
    this.setData({
      specialEffects: wx.getStorageSync('specialEffects')
    })
    if (this.data.specialEffects) {
      wx.showToast({
        title: '已关闭特效',
        icon: 'none',
        duration: 2000 //持续的时间
      })
    } else {
      wx.showToast({
        title: '已开启特效',
        icon: 'none',
        duration: 2000 //持续的时间
      })
    }
    console.log('关闭特效');
  },
  //关闭声音
  turnoffsoundEffects() {
    console.log(this.data.pullFlow ? '关闭声音' : '开启声音');
    this.setData({
      pullFlow: !this.data.pullFlow
    })
    if (!this.data.pullFlow) {
      // 停止拉流
      stopPlayAll(this.data.livePlayerList, this)
    } else {
      // 开启拉流
      zg = initSDK(this);
      zg && this.getLoginToken();
    }
  },
  //清除公屏
  Clearpublicscreen() {
    console.log('清除公屏');
    let _ = this;
    let timestamp = (Date.parse(new Date()) / 1000).toString();
    let arys = {
      roomId: _.data.roomId,
      userId: app.globalData.user_id,
      token: app.globalData.userToken,
      time: timestamp,
    };
    let _token = axios.encryption(arys);
    let params = {
      roomId: _.data.roomId,
      userId: app.globalData.user_id,
      token: app.globalData.userToken,
      time: timestamp,
      sign: md5.hexMD5(_token),
    };
    axios.axios({
      url: "/chat/cleanscreen",
      data: params
    }).then((res) => {
      if (res.data.status == 0) {
        this.setData({
          messageList: []
        })
        wx.showToast({
          title: res.data.text,
          icon: 'none',
          duration: 2000 //持续的时间
        })
      }
    })
  },
  //编辑欢迎语
  Editorialwelcome() {
    console.log('编辑欢迎语');
    return wx.showToast({
      title: "管理员功能请前往app体验",
      icon: 'none',
      duration: 2000 //持续的时间
    })
  },
  //房间类型
  roomtype() {
    console.log('房间类型');
    return wx.showToast({
      title: "管理员功能请前往app体验",
      icon: 'none',
      duration: 2000 //持续的时间
    })
  },
  //举报房间
  reportingRoom(data) {
    this.setData({
      features: false
    })
    console.log(data);
    let nickname = data.currentTarget.dataset.nickname
    let reportId = data.currentTarget.dataset.user_id
    wx.navigateTo({
      url: '/pages/report/report?reportId=' + reportId + '&nickname=' + nickname,
    })
  },
  close_myCanvas3() {
    this.setData({
      svga_isshow: false,
      approachAnimation: false
    })
  },
  statechange(e) {
    console.log(e);
  },
  //自己显示送礼物
  async playSvga3(svgaUrl, IDclassname) {
    if (this.data.specialEffects) {
      return
    }
    if (this.data.process) {
      return
    }
    try {
      let that = this
      that.setData({
        svga_isshow: true,
        process: true,
      })
      const parser = new Parser();
      const player = new Player;
      player.loops = 1
      await player.setCanvas(IDclassname)
      const videoItem = await parser.load(svgaUrl);
      await player.setVideoItem(videoItem);
      player.startAnimation();
      player.onFinished(res => {
        console.log("动画停止了")
        that.setData({
          svga_isshow: false,
          process: false,
        })
      })
    } catch (error) {
      console.log(error);
    }
  },

  //进场特效
  async playSvga5() {
    try {
      let that = this
      that.setData({
        joinRoom_s:true,
        svga5_state: false
      })
      const parser = new Parser();
      const player = new Player;
      player.loops = 1
      await player.setCanvas('#myCanvas5')
      await Room_cache_image('https://xunyinjiaoyou.oss-cn-qingdao.aliyuncs.com/static/images/yutu2.svga', 'yutu2').then((image_filepath) => {
        that.setData({
          image_filepath: image_filepath
        })
      })
      const videoItem = await parser.load(that.data.image_filepath);
      await player.setImage(that.data.play_svge5[0].result.fromUserHeadPic, 'headpic');
      await player.setImage(that.data.img_level + that.data.play_svge5[0].result.level + '.png', 'level');
      await player.setImage(that.data.img_charm + that.data.play_svge5[0].result.charmPic + '.png', 'charmPic');
      player.setText({
        text: that.data.play_svge5[0].result.userName + that.data.play_svge5[0].result.messageContent,
        size: 24,
        color: "white",
        offset: {
          y: 10
        }
      }, 'text');
      await player.setVideoItem(videoItem);
      player.startAnimation();
      player.onFinished(res => {
        console.log("动画停止了")
        that.data.play_svge5.shift();
        that.setData({
          svga5_state: true,
          joinRoom_s: false, //进场特效
        })
        if (that.data.play_svge5.length > 0) {
          that.playSvga5()
        }
      })
    } catch (error) {
      console.log(error);
    }
  },
  //幸运礼物特效 删除
  async playSvga6(gift_luck, IDclassname) {
    try {
      let that = this
      const parser = new Parser();
      const player = new Player;
      player.loops = 1
      await player.setCanvas(IDclassname)
      const videoItem = await parser.load("http://img.xunyinjiaoyou.com" + gift_luck.url);
      await player.setImage("http://img.xunyinjiaoyou.com" + gift_luck.list[0], 'giftIcon');
      await player.setVideoItem(videoItem);
      player.startAnimation();
      player.onFinished(res => {
        console.log("动画停止了")
        that.setData({
          approachAnimation: false,
          luckbox_: false, //进场特效
        })
      })
    } catch (error) {
      console.log(error);
    }
  },


  //房间背景
  async playSvga7(gift_luck, IDclassname, loop) {
    console.log("开始播放svga7背景");
    console.log(gift_luck);
    try {
      const parser = new Parser();
      const player = new Player;
      player.loops = loop
      await player.setCanvas(IDclassname)
      const videoItem = await parser.load(gift_luck);
      await player.setVideoItem(videoItem);
      player.startAnimation();
      player.onFinished(res => {
        console.log("动画停止了")
      })
    } catch (error) {
      console.log(error);
    }
  },
  //发送欢迎语
  Clicksend(data) {
    let item = {
      "charm": this.data.user_Info_list.charmPic,
      "fromUserHeadPic": this.data.user_Info_list.headPic,
      "isNew": this.data.user_Info_list.isNew,
      "level": this.data.user_Info_list.levelPic,
      "messageContent": '欢迎' + data.currentTarget.dataset.welcomewords + '来到房间',
      "userName": this.data.user_Info_list.nickname,
      "isPerfectNum": this.data.user_Info_list.isPerfectNum,
      "adminType": this.data.list.room_info.admin_type,
    }
    this.sendMsg(item, "text")
  },
  //发送快捷短语
  phrasesend(data) {
    let item = {
      "charm": this.data.user_Info_list.charmPic,
      "fromUserHeadPic": this.data.user_Info_list.headPic,
      "isNew": this.data.user_Info_list.isNew,
      "level": this.data.user_Info_list.levelPic,
      "messageContent": data.currentTarget.dataset.welcomewords,
      "userName": this.data.user_Info_list.nickname,
      "isPerfectNum": this.data.user_Info_list.isPerfectNum,
      "adminType": this.data.list.room_info.admin_type,
    }
    this.sendMsg(item, "text")
  },
  //爆灯欢迎
  BurstLamp() {
    let BurstLamp_ = {
      gifUrl: 'http://img.xunyinjiaoyou.com/static/face/gif/baodeng.gif',
      icon: 'http://img.xunyinjiaoyou.com/static/face/baodeng.png',
      name: "爆灯",
      path: "baodeng",
    }
    this.sendMsg(BurstLamp_, "chatroomFace")
  },
  //发送输入框文本消息
  sendMsg_text() {
    if (!this.data.inputMessage) {
      return
    }
    let item = {
      "charm": this.data.user_Info_list.charmPic,
      "fromUserHeadPic": this.data.user_Info_list.headPic,
      "isNew": this.data.user_Info_list.isNew,
      "level": this.data.user_Info_list.levelPic,
      "messageContent": this.data.inputMessage,
      "userName": this.data.user_Info_list.nickname,
      "isPerfectNum": this.data.user_Info_list.isPerfectNum,
      "adminType": this.data.list.room_info.admin_type,
    }
    this.sendMsg(item, "text")
  },
  //点击表情包发送
  send_ex(data) {
    if (data.currentTarget.dataset.expore.path == "maixu") {
      this.setData({
        number: Math.ceil(Math.random() * 8)
      })
    } else {
      this.setData({
        number: null,
      })
    }
    this.sendMsg(data.currentTarget.dataset.expore, "chatroomFace")
  },
  sendMsg(item, type) { //客户端发送消息
    if (type == "text") {
      let message = {
        "result": {
          "charm": this.data.user_Info_list.charmPic,
          "fromUserHeadPic": this.data.user_Info_list.headPic,
          "isNew": this.data.user_Info_list.isNew,
          "level": this.data.user_Info_list.levelPic,
          "messageContent": item.messageContent,
          "userId": this.data.user_Info_list.userId,
          "userName": this.data.user_Info_list.nickname,
          "isPerfectNum": this.data.user_Info_list.isPerfectNum,
          "adminType": this.data.myUserInfo.adminType,
        },
        "type": "text" //文本内容
      }
      this.setData({
        messageList: [...this.data.messageList, message],
        inputMessage: "",
      });
      this.sed_message(message) //发送消息
    } else if (type == "chatroomFace") {
      let message = {
        "result": {
          "gifUrl": item.gifUrl,
          "icon": item.icon,
          "isNew": this.data.user_Info_list.isNew,
          "level": this.data.user_Info_list.levelPic,
          "charm": this.data.user_Info_list.charmPic,
          "name": item.name,
          "path": item.path,
          "userId": this.data.user_Info_list.userId,
          "number": this.data.number ? this.data.number : '0',
          "nickname": this.data.user_Info_list.nickname,
        },
        "type": "chatroomFace"
      }
      this.sed_message(message)
    } else if (type == "joinRoom") {
      let message = {
        "result": {
          "charmPic": item.charmPic,
          "driver_info": item.driver_info, //座驾
          "driver_name": item.driver_name, //座驾名字
          "effect": item.effect, //进场特效
          "fromUserHeadPic": item.fromUserHeadPic,
          "isNew": item.isNew,
          "level": item.level,
          "messageContent": '进入了房间',
          "userId": item.userId,
          "userName": '我',

        },
        "type": "joinRoom"
      }
      if (message.result.driver_info) { //座驾
        this.setData({
          approachAnimation: true, //进场特效
        })
        this.playSvga4(message.result.driver_info, "#myCanvas3", '1')
      }
      if (message.result.effect) { //进场动画
        // this.setData({
        //   joinRoom_s: true,
        // })
        this.getIntoQueue_Svge5(message)
      }
      this.setData({
        messageList: [...this.data.messageList, message],
      })
    }
  },
  getIntoQueue_Svge5(message) {
    this.setData({
      play_svge5: [...this.data.play_svge5, message],
    })
    if (this.data.svga5_state) {
      this.playSvga5()
    }
  },

  // 发送sdk消息
  async sed_message(message) {
    let _ = this;
    try {
      const isSent = await zg.sendBroadcastMessage(this.data.roomId, JSON.stringify(message))
      if (message.type == "chatroomFace") {
        let that = this;
        that.data.list.userlist.forEach(item => {
          if (item.user_id == that.data.user_Info_list.userId) {
            if (that.data.isemoticon == null) {
              this.setData({
                expression: false,
                isemoticon: item.position,
                messageList_: message,
              })
              let timer
              clearTimeout(timer)
              timer = setTimeout(() => { //设置延迟执行
                if (message.result.path == "maixu") {
                  this.setData({
                    maixu: true,
                    maixu_image: 'https://img.xunyinjiaoyou.com/static/face/maixu/ic_mx_' + this.data.number + '.png',
                  })
                }
                let timer2
                clearTimeout(timer2)
                timer2 = setTimeout(() => { //设置延迟执行 
                  this.setData({
                    isemoticon: null,
                    maixu: false,
                    messageList: [...this.data.messageList, message],
                  })
                }, 3000);
              }, 3500);
            }
          }
        });
      } else if (message.type == "text") {
        this.setData({
          issend_: false,
          inputMessage_: "聊点什么吧...",
        })
      }
      _.scrollTop_length()
    } catch (error) {
      console.log('>>> 发送失败: ', error);
    };
  },
  issvga(value) {
    if (value) {
      let type = [];
      type = value.split(".").pop();
      if (type == 'svga') {
        return true;
      } else {
        return false;
      }
    }
  },
  //点击model管理员权限
  isguan(data) {
    console.log(data.currentTarget.dataset.status);
    if (data.currentTarget.dataset.status) {
      this.setData({
        "jurisdiction[1].fun_name": "解除禁言"
      })
    } else {
      this.setData({
        "jurisdiction[1].fun_name": "设置禁言"
      })
    }
    this.setData({
      isguan: !this.data.isguan
    })
  },

  //开启麦克风
  microPhone() {
    let that = this;
    var result = that.data.list.userlist.some(function (item) {
      if (item.user_id == app.globalData.user_id) {
        return true
      }
    })
    if (!result) {
      return wx.showToast({
        title: "请上麦后开启麦克风",
        icon: 'none',
        duration: 2000 //持续的时间
      })
    } else {
      that.setData({
        microPhone: !that.data.microPhone
      })
    }
    if (that.data.microPhone) { //开麦
      if (that.data.zego_token_new_) {
        startPush(that); //开启推流
      } else {
        that.Turnonthemicrophone()
      }
      // startPush(that); //开启推流
    } else {
      console.log("停止推流");
      zg.stopPublishingStream(app.globalData.user_id.toString());
      that.data.livePusher.stop();
      that.setData({
        livePusherUrl: '',
        microPhone: false, //自己静音 
      });
    }
  },

  //获取newtoken权鉴
  Turnonthemicrophone() {
    let that = this;
    let params = {
      type: '2',
      roomId: this.data.roomId,
      userId: app.globalData.user_id,
      token: app.globalData.userToken,
    };
    axios.axios({
      url: "/chat/publishstream",
      data: params
    }).then((res) => {
      if (res.data.status === 0) {
        that.setData({
          zego_token_new_: res.data.result.zego_token
        })
        if (zg.renewToken(res.data.result.zego_token, that.data.roomId)) { //鉴权
          zg.renewToken(res.data.result.zego_token, that.data.roomId)
          startPush(that); //开启推流
        }
      }
    })
  },
  onPushNetStateChange(e) {
    console.log(e);
    //透传网络状态事件给 SDK，type 1 推流
    zg.updatePlayerNetStatus(this.data.livePusherUrl, e, 1);
  },
  //小于30禁音
  onbindaudiovolumenotify(e) {
    console.log("说话的音量", e.detail.volume)
    // if (e.detail.volume < 30) {
    //   this.setData({
    //     microPhone_: true
    //   })
    // } else {
    //   this.setData({
    //     microPhone_: false
    //   })
    // }
  },
  onPlayAudiovolumenotify(e) {
    console.log('接收到的声音', e.detail.volume);
    // if (e.detail.volume < 30) {
    //   this.setData({
    //     microPhone_: true
    //   })
    // } else {
    //   this.setData({
    //     microPhone_: false
    //   })
    // }
  },
  //点击模态框
  noexpression() {
    this.setData({
      expression: false,
    })
  },

  //点击省略号
  box_rule() {
    this.setData({
      box_rule: !this.data.box_rule
    })
  },
  //更多功能
  features() {
    this.setData({
      // specialEffects:wx.getStorageSync('specialEffects')?wx.getStorageSync('specialEffects'):false,
      features: true
    })
  },
  features2() {
    this.setData({
      features: false
    })
  },
  //用户
  roomOnline() {
    this.setData({
      type: '2',
      roomOnlineRoom_list: true
    })
    this.getList()
  },
  roomOnline2() {
    this.setData({
      roomOnline: false
    })
  },
  roomOnlineRoom_list() {
    this.setData({
      roomOnlineRoom_list: true
    })
    this.getRank()
  },
  roomOnlineRoom_list_() {
    this.setData({
      roomOnlineRoom_list: false
    })
  },

  getList() {
    let params = {
      userId: app.globalData.user_id,
      token: app.globalData.userToken,
      roomId: this.data.roomId,
      page: this.data.page,
    };
    axios.axios({
      url: "/chat/onlineUserListV2",
      data: params
    }).then((res) => {
      console.log(res.data.result),
        this.setData({
          user_count: res.data.result.user_count,
          onlineList: res.data.result.user_list
        })
    })
  },

  typeChange(data) {
    let typeChange = data.currentTarget.dataset.typechange
    this.setData({
      type: typeChange
    })
    if (typeChange == '2') {
      this.getList()
    } else {
      this.getRank()
    }
  },
  dateChange(data) {
    this.setData({
      dateType: data.currentTarget.dataset.datechange
    })
    this.getRank()
  },
  topersonpage(data) {
    // console.log(data.currentTarget.dataset.id)
    wx.navigateTo({
      url: '/pages/personpage/personpage?memberId=' + data.currentTarget.dataset.id,
    })
  },
  tome(data) {
    let memberId;
    if (data.currentTarget) {
      memberId = data.currentTarget.dataset.memberid
    } else {
      memberId = data
    }
    wx.navigateTo({
      url: '/pages/me/me?memberId=' + memberId,
    })
  },
  getRank() {
    let timestamp = (Date.parse(new Date()) / 1000).toString();
    let _token =
      "userId=" +
      app.globalData.user_id +
      "&type=" +
      this.data.type +
      "&token=" +
      app.globalData.userToken +
      "&time=" +
      timestamp +
      "&roomId=" +
      this.data.roomId +
      "&dateType=" +
      this.data.dateType +
      "&wPQvCAOU$lbIyg9o2wVg0Dt1k^zy&SaX";
    let params = {
      userId: app.globalData.user_id,
      token: app.globalData.userToken,
      type: this.data.type.toString(),
      roomId: this.data.roomId,
      dateType: this.data.dateType,
      time: timestamp,
      sign: md5.hexMD5(_token),
    };
    axios.axios({
      url: "/chat/rankRoom",
      data: params
    }).then((res) => {
      console.log(res.data.result)
      this.setData({
        rankList1: res.data.result.list.splice(0, 3),
        rankList2: res.data.result.list,
        my_info: res.data.result.my_info,
      })
    })
  },
  //显示表情包
  expression() {
    var result = this.data.list.userlist.some(function (item) {
      if (item.user_id === app.globalData.user_id) {
        return true
      }
    })
    if (!result) {
      return wx.showToast({
        title: "未上麦不能发送表情",
        icon: 'none',
        duration: 2000 //持续的时间
      })
    }
    this.setData({
      expression: true,
    })
    let timestamp = (Date.parse(new Date()) / 1000).toString();
    let _token =
      "userId=" +
      app.globalData.user_id +
      "&token=" +
      app.globalData.userToken +
      "&time=" +
      timestamp +
      "&wPQvCAOU$lbIyg9o2wVg0Dt1k^zy&SaX";
    let params = {
      userId: app.globalData.user_id,
      token: app.globalData.userToken,
      time: timestamp,
      sign: md5.hexMD5(_token),
    };
    axios.axios({
      url: "/chat/expression",
      data: params
    }).then((res) => {
      // console.log(res.data.result),
      this.setData({
        expressionEnsemble: res.data.result,
      })
    })
  },
  clickoverlay_() {
    this.setData({
      disable: false,
      giftShow: false
    })
  },
  //显示送礼物
  opengift_() {
    if (this.data.showgiftList1.length) {
      this.setData({
        giftShow: true,
        changegift_userlist: 0, //是否全麦0否
      })
    } else {
      let timestamp = (Date.parse(new Date()) / 1000).toString();
      let _token =
        "userId=" +
        app.globalData.user_id +
        "&token=" +
        app.globalData.userToken +
        "&time=" +
        timestamp +
        "&wPQvCAOU$lbIyg9o2wVg0Dt1k^zy&SaX";
      let params = {
        userId: app.globalData.user_id,
        token: app.globalData.userToken,
        time: timestamp,
        sign: md5.hexMD5(_token),
      };
      axios.axios({
        url: "/gift/giftList",
        data: params
      }).then((res) => {
        console.log(res.data.result),
          this.setData({
            showgiftList1: res.data.result.daily.slice(0, 8),
            showgiftList2: res.data.result.daily.slice(8, 16),
            showgiftList3: res.data.result.daily.slice(16, 24),
            showgiftList4: res.data.result.daily.slice(24, 32),
            baggiftList: res.data.result.bag,
            luckgiftList: res.data.result.boxGift,
            daygiftList: res.data.result.daily,
            giftShow: true,
            diamond: res.data.result.userMoney,
            gift_id: res.data.result.daily[0].id,
            giftName: res.data.result.daily[0].giftName,
            // sendNumList: res.data.result.daily[0].giftNum
          })
      })
    }

  },
  //更新礼物
  luckBox() {
    let params = {
      userId: app.globalData.user_id,
      token: app.globalData.userToken,
    };
    axios.axios({
      url: "/gift/giftList",
      data: params
    }).then((res) => {
      this.setData({
        luckBox: res.data.result.boxGift
      })
    })
  },
  //更新礼物
  opengift_2() {
    let timestamp = (Date.parse(new Date()) / 1000).toString();
    let _token =
      "userId=" +
      app.globalData.user_id +
      "&token=" +
      app.globalData.userToken +
      "&time=" +
      timestamp +
      "&wPQvCAOU$lbIyg9o2wVg0Dt1k^zy&SaX";
    let params = {
      userId: app.globalData.user_id,
      token: app.globalData.userToken,
      time: timestamp,
      sign: md5.hexMD5(_token),
    };
    axios.axios({
      url: "/gift/giftList",
      data: params
    }).then((res) => {
      // console.log(res.data.result),
      this.setData({
        baggiftList: res.data.result.bag,
        luckgiftList: res.data.result.boxGift,
        daygiftList: res.data.result.daily,
        showgiftList1: res.data.result.bag.slice(0, 8),
        showgiftList2: res.data.result.bag.slice(8, 16),
        showgiftList3: res.data.result.bag.slice(16, 24),
        showgiftList4: res.data.result.bag.slice(24, 32),
      })
    })
  },
  opengift() {
    this.setData({
      gift_userid: []
    })
    this.opengift_();
    this.user_list();
  },
  // 刷新数据收礼物人
  user_list() {
    var user_list = [];
    this.data.list.userlist.forEach(function (item) {
      // console.log(item);
      item.upshow = false; //r = array[0]的所有数据，这样直接 r.新属性 = 属性值 即可
      if (item.user_id > 0 && item.user_id != app.globalData.user_id) {
        return user_list.push(item)
      }
    })
    this.setData({
      user_list: user_list
    })
  },

  //显示可选数量
  showsendnum() {
    this.setData({
      sendNumShow: !this.data.sendNumShow
    })
  },
  //更改可送数量
  changesendNum(data) {
    this.setData({
      sendNum: data.currentTarget.dataset.num,
      sendNumShow: false
    })
    // console.log(data.currentTarget.dataset.num);
  },
  //切换礼物类型
  sendtopChaneg(data) {
    this.setData({
      showgiftList1: [],
      showgiftList2: [],
      showgiftList3: [],
      showgiftList4: [],
    })
    // console.log(data.currentTarget.dataset)
    switch (data.currentTarget.dataset.num) {
      case "0":
        this.setData({
          showgiftList1: this.data.daygiftList.slice(0, 8),
          showgiftList2: this.data.daygiftList.slice(8, 16),
          showgiftList3: this.data.daygiftList.slice(16, 24),
          showgiftList4: this.data.daygiftList.slice(24, 32),
          gift_id: this.data.daygiftList[0].id,
          giftName: this.data.daygiftList[0].giftName,
          gift_imgicon: this.data.daygiftList[0].icon,
          imageFile: this.data.daygiftList[0].imageFile,
          giftName: this.data.daygiftList[0].giftName,
          giftMoney: this.data.daygiftList[0].money,
          // sendNum: this.data.daygiftList[0].myNum,
          // sendNumList: this.data.daygiftList[0].giftNum
        })
        break;
      case "1":
        if (this.data.baggiftList[0]) {
          this.setData({
            showgiftList1: this.data.baggiftList.slice(0, 8),
            showgiftList2: this.data.baggiftList.slice(8, 16),
            showgiftList3: this.data.baggiftList.slice(16),
            gift_id: this.data.baggiftList[0].id,
            giftName: this.data.baggiftList[0].giftName,
            gift_imgicon: this.data.baggiftList[0].icon,
            imageFile: this.data.baggiftList[0].imageFile,
            giftName: this.data.baggiftList[0].giftName,
            giftMoney: this.data.baggiftList[0].money,

            // sendNum: this.data.baggiftList[0].myNum,
            // sendNumList: this.data.baggiftList[0].giftNum
          })
        } else {
          //背包为空
          this.setData({
            showgiftList1: this.data.baggiftList.slice(0, 8),
            showgiftList2: this.data.baggiftList.slice(8, 16),
            showgiftList3: this.data.baggiftList.slice(16),
          })
        }
        break;
      case "2":
        this.luckBox()
        this.setData({
          showgiftList1: this.data.luckgiftList,
          showgiftList2: [],
          gift_id: this.data.luckgiftList[0].id,
          giftName: this.data.luckgiftList[0].giftName,
          gift_imgicon: this.data.luckgiftList[0].icon,
          imageFile: this.data.luckgiftList[0].imageFile,
          sendNum: this.data.luckgiftList[0].myNum + 1,
          giftName: this.data.luckgiftList[0].giftName,
          giftMoney: this.data.luckgiftList[0].money,

        })
        break;
    }
    this.setData({
      sendgiftNum: parseInt(data.currentTarget.dataset.num),
      showgiftNum1: 0,
      // showgiftNum2: 8,
    })
  },
  //去幸运魔盒
  toluckyBox() {
    let url = "https://h5.xunyinjiaoyou.com/h5/#/luckyBox";
    wx.navigateTo({
      url: '../link/link?url=' + url
    })
  },
  //选中的送礼物人
  changegift_gif(data) {
    var list_name_ = [];
    this.data.user_list.forEach((item, index, arr) => {
      if (data.currentTarget.dataset.index == index) {
        arr[index].upshow = !arr[index].upshow;
      }
      return list_name_.push(item)
    });
    this.setData({
      user_list: list_name_
    })

    // console.log(axios.isupshow(this.data.user_list));
    this.data.user_list.forEach((item) => { //全选即全麦
      if (item.upshow == false || axios.isupshow(this.data.user_list) == true) {
        this.setData({
          changegift_userlist: 0
        })
      } else {
        this.setData({
          changegift_userlist: 1
        })
      }
    });

    var gift_userid = [];
    if (this.data.user_list.length == 1) {
      if (this.data.user_list[0].upshow) {
        gift_userid.push(this.data.user_list[0])
      }
    } else {
      this.data.user_list.forEach((item) => {
        if (item.upshow) {
          gift_userid.push(item)
        }
      });
    }
    this.setData({
      gift_userid: gift_userid
    })
    console.log(this.data.gift_userid);
    // if (!this.data.gift_userid.toString()) {
    //   return wx.showToast({
    //     icon: 'none',
    //     duration: 2000 //持续的时间
    //   })
    // }
    // console.log(this.data.user_list);
  },
  //全选送礼物
  changegift_userlist() {
    if (this.data.disable) {
      return wx.showToast({
        title: "不可点击",
        icon: 'none',
        duration: 2000 //持续的时间
      })
    }
    var arr = [];
    if (this.data.changegift_userlist == 1) {
      this.setData({
        changegift_userlist: 0
      })
      this.data.user_list.forEach((item) => {
        item.upshow = false;
        arr.push(item)
      });
      this.setData({
        user_list: arr
      })
      console.log(this.data.user_list);
    } else {
      this.setData({
        changegift_userlist: 1
      })
      this.data.user_list.forEach((item) => {
        item.upshow = true;
        arr.push(item)
      });
      this.setData({
        user_list: arr
      })

    }
    var gift_userid = [];
    if (this.data.user_list.length == 1) {
      if (this.data.user_list[0].upshow) {
        gift_userid.push(this.data.user_list[0])
      }
    } else {
      this.data.user_list.forEach((item) => {
        if (item.upshow) {
          gift_userid.push(item)
        }
      });
    }
    this.setData({
      gift_userid: gift_userid
    })
    console.log(this.data.gift_userid);
  },
  //更改第一页下标
  changegift1(data) {
    this.setData({
      showgiftNum1: parseInt(data.currentTarget.dataset.index),
      showgiftNum2: 8,
      // sendNumList: this.data.showgiftList1[parseInt(data.currentTarget.dataset.index)].giftNum,
      gift_id: this.data.showgiftList1[parseInt(data.currentTarget.dataset.index)].id,
      sendNum: 1,
      sendNumShow: false,
      gift_imgicon: this.data.showgiftList1[parseInt(data.currentTarget.dataset.index)].icon,
      imageFile: this.data.showgiftList1[parseInt(data.currentTarget.dataset.index)].imageFile,
      giftName: this.data.showgiftList1[parseInt(data.currentTarget.dataset.index)].giftName,
      giftMoney: this.data.showgiftList1[parseInt(data.currentTarget.dataset.index)].money,
    })
  },
  //更改第二页下标
  changegift2(data) {
    this.setData({
      showgiftNum2: parseInt(data.currentTarget.dataset.index),
      showgiftNum1: parseInt(data.currentTarget.dataset.index),
      // sendNumList: this.data.showgiftList2[parseInt(data.currentTarget.dataset.index)].giftNum,
      gift_id: this.data.showgiftList2[parseInt(data.currentTarget.dataset.index)].id,
      sendNum: 1,
      sendNumShow: false,
      gift_imgicon: this.data.showgiftList2[parseInt(data.currentTarget.dataset.index)].icon,
      imageFile: this.data.showgiftList2[parseInt(data.currentTarget.dataset.index)].imageFile,
      giftName: this.data.showgiftList2[parseInt(data.currentTarget.dataset.index)].giftName,
      giftMoney: this.data.showgiftList1[parseInt(data.currentTarget.dataset.index)].money,

    })
  },
  //更改第三页下标
  changegift3(data) {
    this.setData({
      showgiftNum3: parseInt(data.currentTarget.dataset.index),
      showgiftNum1: parseInt(data.currentTarget.dataset.index),
      // sendNumList: this.data.showgiftList3[parseInt(data.currentTarget.dataset.index)].giftNum,
      gift_id: this.data.showgiftList3[parseInt(data.currentTarget.dataset.index)].id,
      sendNum: 1,
      sendNumShow: false,
      gift_imgicon: this.data.showgiftList3[parseInt(data.currentTarget.dataset.index)].icon,
      imageFile: this.data.showgiftList3[parseInt(data.currentTarget.dataset.index)].imageFile,
      giftName: this.data.showgiftList3[parseInt(data.currentTarget.dataset.index)].giftName,
      giftMoney: this.data.showgiftList1[parseInt(data.currentTarget.dataset.index)].money,
    })
  },
  //更改第四页下标
  changegift4(data) {
    this.setData({
      showgiftNum4: parseInt(data.currentTarget.dataset.index),
      showgiftNum1: parseInt(data.currentTarget.dataset.index),
      // sendNumList: this.data.showgiftList3[parseInt(data.currentTarget.dataset.index)].giftNum,
      gift_id: this.data.showgiftList4[parseInt(data.currentTarget.dataset.index)].id,
      sendNum: 1,
      sendNumShow: false,
      gift_imgicon: this.data.showgiftList4[parseInt(data.currentTarget.dataset.index)].icon,
      imageFile: this.data.showgiftList4[parseInt(data.currentTarget.dataset.index)].imageFile,
      giftName: this.data.showgiftList4[parseInt(data.currentTarget.dataset.index)].giftName,
      giftMoney: this.data.showgiftList1[parseInt(data.currentTarget.dataset.index)].money,

    })
  },
  //点击卡片送礼
  giftGiving(data) {
    console.log(data.currentTarget.dataset.give_id);
    var list = [];
    data.currentTarget.dataset.give_id.upshow = true;
    list.push(data.currentTarget.dataset.give_id)
    let tesult = list.map(item => {
      console.log(item);
      return {
        user_id: item.userId ? item.userId : item.user_id,
        nickname: item.nickname,
        upshow: item.upshow,
        perfect_number: item.perfect_number
      }
    })
    this.setData({
      gift_userid: tesult,
      user_list: tesult,
      cardShow: false,
      disable: true,
      // changegift_userlist: 1,
    })
    this.opengift_()
    console.log(this.data.user_list);
  },
  copy() {
    wx.setClipboardData({
      data: '' + this.data.personInfo.perfect_number,
    })
  },
  //赠送
  givingGift() {
    // console.log(this.data.user_list);
    if (!this.data.gift_id) {
      return wx.showToast({
        title: "请选择礼物",
        icon: 'none',
        duration: 2000 //持续的时间
      })
    }
    if (!this.data.gift_userid[0]) {
      return wx.showToast({
        title: '请选择接收礼物人',
        icon: 'none',
        duration: 2000 //持续的时间
      })
    }
    var gift_userid = [];
    this.data.gift_userid.forEach((item) => {
      gift_userid.push(item.user_id)
    });
    // console.log(gift_userid);
    let obj_gift_userid = gift_userid.join(',')
    // console.log(obj_gift_userid);
    let timestamp = (Date.parse(new Date()) / 1000).toString();
    let giftCate = this.data.sendgiftNum + 1;
    let params = {
      giftId: this.data.gift_id,
      userId: app.globalData.user_id,
      num: this.data.sendNum,
      sellerId: obj_gift_userid,
      roomId: this.data.roomId,
      giftCate: this.data.sendgiftNum + 1,
      token: app.globalData.userToken,
      time: timestamp,
    };
    axios.axios({
      url: "/gift/givingGift",
      data: params
    }).then((res) => {
      if (res.data.status == 0) {
        if (this.data.sendgiftNum == '1') { //送背包礼物
          this.setData({
            gift_imgicon_wu: this.data.gift_imgicon
          })
          this.opengift_2(); //刷新背包
        }
        this.setData({
          diamond: res.data.result.userMoney,
        })
      } else {
        wx.showToast({
          title: res.data.text,
          icon: 'none',
          duration: 2000 //持续的时间
        })
      }
    })
  },
  //收藏
  isCollect(data) {
    let timestamp = (Date.parse(new Date()) / 1000).toString();
    let arys = {
      roomId: this.data.roomId,
      userId: app.globalData.user_id,
      token: app.globalData.userToken,
      time: timestamp,
      type: data.currentTarget.dataset.iscollect,
    };
    let _token = axios.encryption(arys);
    let params = {
      roomId: this.data.roomId,
      userId: app.globalData.user_id,
      token: app.globalData.userToken,
      type: data.currentTarget.dataset.iscollect,
      time: timestamp,
      sign: md5.hexMD5(_token),
    };
    axios.axios({
      url: "/chat/follow_room",
      data: params
    }).then((res) => {
      if (res.data.status == 0) {
        this.setData({
          "myUserInfo.isCollect": this.data.myUserInfo.isCollect == '0' ? '1' : '0'
        })
      }
      wx.showToast({
        title: res.data.text,
        icon: 'none',
        duration: 2000 //持续的时间 
      })
    })
  },
  //前往在线用户
  toOnline() {
    wx.navigateTo({
      url: '/pages/roomOnline/roomOnline?roomId=' + this.data.roomId,
    })
  },

  //前往房间排行榜
  toroomRank() {
    // console.log(this.data.roomId);
    wx.navigateTo({
      url: '/pages/roomRank/roomRank?roomId=' + this.data.roomId,
    })
  },
  //显示玩法介绍
  introduceChange() {
    this.setData({
      introduceShow: true
    })
  },
  //隐藏
  introduceChange4() {
    this.setData({
      businessCard: false
    })
  },
  //显示房间信息
  introduceChange3() {
    this.chatFullInfo(), //
      this.setData({
        businessCard: true
      })
  },
  //显示送礼物model
  selext_model() {
    if (this.data.disable) {
      return wx.showToast({
        title: '不可点击',
        icon: 'none',
        duration: 2000 //持续的时间
      })
    }
    this.setData({
      selext_model: true
    })
  },
  //关闭显示送礼物model
  selext_model_close() {
    this.setData({
      selext_model: false
    })
  },
  //关闭玩法介绍
  introduceChange2() {
    this.setData({
      introduceShow: false,
    })
  },
  //防止事件冒泡
  cardClick() {},
  //房间全部信息
  chatFullInfo() {
    let timestamp = (Date.parse(new Date()) / 1000).toString();
    let arys = {
      roomId: this.data.roomId,
      userId: app.globalData.user_id,
      token: app.globalData.userToken,
      time: timestamp,
    };
    let _token = axios.encryption(arys);
    let params = {
      roomId: this.data.roomId,
      userId: app.globalData.user_id,
      token: app.globalData.userToken,
      time: timestamp,
      sign: md5.hexMD5(_token),
    };
    axios.axios({
      url: "/chat/chatFullInfo",
      data: params
    }).then((res) => {
      console.log(res.data.result);
      this.setData({
        chatFullInfo: res.data.result,
      })
    })
  },
  //点击麦位
  cardChange(data) {
    // console.log(data.currentTarget.dataset.list);
    if (data.currentTarget.dataset.list.user_id == 0) { //没人 
      if (this.data.isadministrators) { //麦位没人管理员操作
        let locking; //锁定
        let movePosition; //移动麦位
        if (data.currentTarget.dataset.list.status == 1) {
          locking = true
        } else {
          locking = false
        }
        if (axios.isgetStorageSync("userlist_", app.globalData.user_id)) {
          movePosition = false
        } else {
          movePosition = true
        }
        wx.showActionSheet({
          itemList: [locking ? '锁定' : '解除锁定', '抱人上麦', movePosition ? '上麦' : '移动到此麦位'],
          itemColor: '#000000',
          success: res => {
            if (res.tapIndex === 0) {
              this.lockPosition(locking ? 1 : 2, data.currentTarget.dataset.list.position)
            } else if (res.tapIndex === 1) {
              console.log('点击了抱人上麦');
              this.setData({
                position_bao: data.currentTarget.dataset.list.position,
              })
              this.roomOnline()
            } else {
              // this.ismap_youren(data.currentTarget.dataset.list.position)
              this.goWheat("/chat/movePosition", data.currentTarget.dataset.list.position.toString())
            }
          }
        })
      } else { //麦位没人普通用户操作
        // this.ismap_youren(data.currentTarget.dataset.list.position)
        this.goWheat("/chat/movePosition", data.currentTarget.dataset.list.position.toString())
      }
    } else { //有人，显示卡片
      if (data.currentTarget.dataset.list.user_id == app.globalData.user_id) { //点击自己麦序
        if (this.data.isadministrators) { //管理员点击自己头像
          // wx.showActionSheet({
          //   // itemList: ['抱人上麦', '下麦'],
          //   itemList: ['下麦'],
          //   itemColor: '#000000',
          //   success: res => {
          //     // if (res.tapIndex === 0) {
          //     //   wx.navigateTo({
          //     //     url: '/pages/roomOnline/roomOnline?roomId=' + this.data.roomId + "&request=" + "1",
          //     //   })
          //     // } else if (res.tapIndex === 1) {
          //     this.leaveWait()
          //     // }
          //   }
          // })
          this.businessCard(data.currentTarget.dataset.list.user_id)
          this.setData({
            cardShow: true,
            isown: true,
            isadministrators: true,
            memberId: data.currentTarget.dataset.list.user_id,
          })
        } else { //我不是管理员点自己头像
          this.businessCard(data.currentTarget.dataset.list.user_id)
          this.setData({
            // nickname: data.currentTarget.dataset.list,
            isown: true,
            cardShow: true,
            memberId: data.currentTarget.dataset.list.user_id,
          })
        }
      } else { //点击他人麦序
        if (this.data.isadministrators) { //我是管理员
          this.businessCard(data.currentTarget.dataset.list.user_id)
          this.setData({
            // nickname: data.currentTarget.dataset.list,
            cardShow: true,
            isown: false,
            isadministrators: true,
            memberId: data.currentTarget.dataset.list.user_id,
          })
        } else { //不是管理员
          this.businessCard(data.currentTarget.dataset.list.user_id)
          this.setData({
            // nickname: data.currentTarget.dataset.list,
            cardShow: true,
            isown: false,
            isadministrators: false,
          })
        }
      }
    }
  },
  tomedalWall(data) {
    wx.navigateTo({
      url: '/pages/medalWall/medalWall?medalWall=' + '1' + '&memberid=' + data.currentTarget.dataset.userid,
    })
  },
  //手指触摸动作开始 记录起点X坐标
  touchstart: function (e) {
    //开始触摸时 重置所有删除
    this.data.messageList_liaot.forEach(function (v, i) {
      if (v.isTouchMove) //只操作为true的
        v.isTouchMove = false;
    })
    this.setData({
      startX: e.changedTouches[0].clientX,
      startY: e.changedTouches[0].clientY,
      messageList_liaot: this.data.messageList_liaot
    })
  },
  //滑动事件处理
  touchmove: function (e) {
    var that = this,
      index = e.currentTarget.dataset.index, //当前索引
      startX = that.data.startX, //开始X坐标
      startY = that.data.startY, //开始Y坐标
      touchMoveX = e.changedTouches[0].clientX, //滑动变化坐标
      touchMoveY = e.changedTouches[0].clientY, //滑动变化坐标
      //获取滑动角度
      angle = that.angle({
        X: startX,
        Y: startY
      }, {
        X: touchMoveX,
        Y: touchMoveY
      });
    that.data.messageList_liaot.forEach(function (v, i) {
      v.isTouchMove = false
      //滑动超过30度角 return
      if (Math.abs(angle) > 30) return;
      if (i == index) {
        if (touchMoveX > startX) //右滑
          v.isTouchMove = false
        else //左滑
          v.isTouchMove = true
      }
    })
    //更新数据
    that.setData({
      messageList_liaot: that.data.messageList_liaot
    })
  },
  /**
   * 计算滑动角度
   * @param {Object} start 起点坐标
   * @param {Object} end 终点坐标
   */
  angle: function (start, end) {
    var _X = end.X - start.X,
      _Y = end.Y - start.Y
    //返回角度 /Math.atan()返回数字的反正切值
    return 360 * Math.atan(_Y / _X) / (2 * Math.PI);
  },
  del: function (e) {
    this.data.messageList_liaot.splice(e.currentTarget.dataset.index, 1)
    this.setData({
      messageList_liaot: this.data.messageList_liaot
    })
    this.delete(e.currentTarget.dataset.indexs.conversationID)
  },
  delete(c2c_id) {
    let promise = this.data.tim.deleteConversation(c2c_id);
    promise.then(function (imResponse) {
      // 删除会话成功
      const {
        conversationID
      } = imResponse.data; // 被删除的会话 ID
      console.log(conversationID);
    }).catch(function (imError) {
      console.warn('deleteConversation error:', imError); // 删除会话失败的相关信息
    });
  },
  // 关注他
  payAttentionToHim(data) {
    console.log(data);
    let url;
    let isfow = data.currentTarget.dataset.isfow
    let followId = data.currentTarget.dataset.followid
    if (isfow == '0') {
      url = "/user/followInsert"
    } else {
      url = "/user/followCancel"
    }
    let timestamp = (Date.parse(new Date()) / 1000).toString();
    let arys = {
      userId: app.globalData.user_id,
      time: timestamp,
      followId: followId,
      token: app.globalData.userToken,
    };
    let _token = axios.encryption(arys);
    let params = {
      followId: followId,
      userId: app.globalData.user_id,
      time: timestamp,
      token: app.globalData.userToken,
      sign: md5.hexMD5(_token),
    };
    axios.axios({
      url: url,
      data: params
    }).then((res) => {
      if (res.data.status == 0) {
        this.businessCard(followId)
      }
      wx.showToast({
        title: res.data.text,
        icon: 'none',
        duration: 2000 //持续的时间
      })
    })
  },
  //抱人上麦
  holdWheat(data) {
    console.log(data);
    let position = this.data.position_bao;
    let memberId = data.currentTarget.dataset.memberid;
    if (!position) {
      return this.tome(memberId)
    }
    let params = {
      roomId: this.data.roomId,
      userId: app.globalData.user_id,
      token: app.globalData.userToken,
      position: position,
      memberId: memberId,
    };
    axios.axios({
      url: "/chat/holdWheat",
      data: params
    }).then((res) => {
      if (res.data.status == 0) {
        wx.showToast({
          title: res.data.text,
          icon: 'none',
          duration: 2000 //持续的时间
        })
        this.setData({
          roomOnlineRoom_list: false,
          position_bao: '',
          roomOnline: false
        })
      } else {
        wx.showToast({
          title: res.data.text,
          icon: 'none',
          duration: 2000 //持续的时间
        })
      }
    })
  },
  //点击卡片
  text_card(data) {
    console.log(data.currentTarget.dataset.item);
    if (data.currentTarget.dataset.item.userId) {
      this.businessCard(data.currentTarget.dataset.item.userId)
    } else {
      this.businessCard(data.currentTarget.dataset.item.userId)
    }
    data.currentTarget.dataset.item.upshow = false;
    let list = [];
    list.push(data.currentTarget.dataset.item)
    this.setData({
      cardShow: true,
      user_list: list,
    })
  },
  //房间个人名片
  businessCard(memberId) {
    this.setData({
      nickname: {}
    })
    let timestamp = (Date.parse(new Date()) / 1000).toString();
    let arys = {
      memberId: memberId,
      roomId: this.data.roomId,
      userId: app.globalData.user_id,
      token: app.globalData.userToken,
      time: timestamp,
    };
    let _token = axios.encryption(arys);
    let params = {
      memberId: memberId,
      roomId: this.data.roomId,
      userId: app.globalData.user_id,
      token: app.globalData.userToken,
      time: timestamp,
      sign: md5.hexMD5(_token),
    };
    axios.axios({
      url: "/chat/userInfo",
      data: params
    }).then((res) => {
      console.log(res.data.result);
      this.setData({
        nickname: res.data.result,
      })
      if (res.data.result.is_gag == '0') {
        this.setData({
          "jurisdiction[1].fun_name": "设置禁言"
        })
      } else {
        this.setData({
          "jurisdiction[1].fun_name": "解除禁言"
        })
      }
    })
  },
  //锁定或者解锁麦位
  lockPosition(type, position) {
    let timestamp = (Date.parse(new Date()) / 1000).toString();
    let _token =
      "userId=" +
      app.globalData.user_id.toString() +
      "&type=" +
      type.toString() +
      "&token=" +
      app.globalData.userToken +
      "&time=" +
      timestamp +
      "&roomId=" +
      this.data.roomId +
      "&position=" +
      position.toString() +
      "&wPQvCAOU$lbIyg9o2wVg0Dt1k^zy&SaX";
    let params = {
      roomId: this.data.roomId,
      userId: app.globalData.user_id.toString(),
      token: app.globalData.userToken,
      time: timestamp,
      type: type.toString(),
      position: position.toString(),
      sign: md5.hexMD5(_token),
    };
    axios.axios({
      url: "/chat/lockPosition",
      data: params
    }).then((res) => {
      if (res.data.status == '0') {
        wx.showToast({
          title: res.data.text,
          icon: 'none',
          duration: 2000 //持续的时间
        })
      }
    })
  },

  //判断麦上是否有人
  ismap_youren(e) {
    // console.log(axios.isgetStorageSync("userlist_", app.globalData.user_id));
    var result = this.data.list.userlist.some(function (item) {
      console.log(app.globalData.user_id);
      console.log(item.user_id);
      if (item.user_id == app.globalData.user_id) {
        return true
      }
    })
    if (result) { //移动麦
      console.log("11111");
      this.goWheat("/chat/movePosition", e.toString())
    }
  },
  //关闭个人卡片
  cardChange2() {
    console.log('123');
    this.setData({
      cardShow: false,
      isguan: false
    })
  },
  //下麦
  lowerWheat() {
    this.leaveWait();
    zg.stopPublishingStream(app.globalData.user_id.toString());
    if (this.data.livePusher) {
      this.data.livePusher.stop();
    }
    this.setData({
      livePusherUrl: '',
      microPhone: false, //自己静音
    });
  },
  bindMessageInput(e) {
    this.setData({
      inputMessage: e.detail.value
    })
  },
  number_s(e) {
    // console.log(e.detail.value);
    this.setData({
      number_s: e.detail.value
    })
  },
  number_zdy(e) {
    console.log(e.detail.value);
    this.setData({
      sendNum: e.detail.value,
    })
  },
  number_zdy_dasle(e) {
    this.setData({
      sendNumShow: false,
      sendNum: e.detail.value,
    })

  },
  number_zdy_nose() {
    this.setData({
      sendNumShow: false
    })
  },
  //移动麦或上麦
  goWheat(e, m) {
    // let timestamp = (Date.parse(new Date()) / 1000).toString();
    // let arys = {
    //   roomId: this.data.roomId,
    //   userId: app.globalData.user_id,
    //   token: app.globalData.userToken,
    //   time: timestamp,
    //   position: m,
    // };
    // let _token = axios.encryption(arys);
    if (m == '0') {
      e = '/chat/movePosition'
    }
    let params = {
      roomId: this.data.roomId,
      userId: app.globalData.user_id,
      token: app.globalData.userToken,
      position: m,
    };
    axios.axios({
      url: e,
      data: params
    }).then((res) => {
      if (res.data.status == 0) {
        // console.log(res);
      } else {
        wx.showToast({
          title: res.data.text,
          icon: 'none',
          duration: 2000 //持续的时间
        })
      }
    })
  },
  //去个人主页
  toperson(data) {
    let user_id = data.currentTarget.dataset.item_s
    wx.navigateTo({
      url: '/pages/me/me?memberId=' + user_id,
    })
  },
  //消息详情
  tomessage_s(data) {
    let datas = JSON.stringify(data.currentTarget.dataset.index_)
    console.log(data);
    wx.navigateTo({
      url: '/pages/messageInfo/messageInfo?index=' + encodeURIComponent(datas),
    })
  },
  //去聊天
  tomessage(data) {
    console.log(data);
    let message_info = {
      perfect_number: data.currentTarget.dataset.index.perfect_number,
      nickName: data.currentTarget.dataset.index.nickname,
    };
    wx.navigateTo({
      url: '/pages/messageInfo/messageInfo?message_info=' + JSON.stringify(message_info),
    })
  },
  //去充值
  torecharge() {
    // this.setData({
    //   is_one: '2',
    //   isJackpot: true,
    // })
    wx.navigateTo({
      url: '/pages/recharge/recharge',
    })
  },
  //关闭抽奖
  closeLuck() {
    this.setData({
      luckShow: false,
      luckNum: 0
    })
  },
  //打开抽奖
  openLuck() {
    this.setData({
      luckShow: true
    })
  },
  //返回抽奖主页
  returnLuck() {
    this.setData({
      luckNum: 0
    })
  },
  //抽奖帮助中心
  helpClick() {
    this.setData({
      luckNum: 1
    })
  },
  //抽奖手气榜
  rankClick() {
    let timestamp = (Date.parse(new Date()) / 1000).toString();
    let _token =
      "userId=" +
      app.globalData.user_id +
      "&token=" +
      app.globalData.userToken +
      "&time=" +
      timestamp +
      "&wPQvCAOU$lbIyg9o2wVg0Dt1k^zy&SaX";
    let params = {
      userId: app.globalData.user_id,
      token: app.globalData.userToken,
      time: timestamp,
      sign: md5.hexMD5(_token),
    };
    axios.axios({
      url: "/lottery/lucktop",
      data: params
    }).then((res) => {
      console.log(res.data.result),
        this.setData({
          luckrankList: res.data.result,
          luckNum: 2
        })
    })
  },
  //奖池
  jackpotClick() {
    let timestamp = (Date.parse(new Date()) / 1000).toString();
    let _token =
      "userId=" +
      app.globalData.user_id +
      "&token=" +
      app.globalData.userToken +
      "&time=" +
      timestamp +
      "&wPQvCAOU$lbIyg9o2wVg0Dt1k^zy&SaX";
    let params = {
      userId: app.globalData.user_id,
      token: app.globalData.userToken,
      time: timestamp,
      sign: md5.hexMD5(_token),
    };
    axios.axios({
      url: "/lottery/boxgiftlist",
      data: params
    }).then((res) => {
      console.log(res.data.result);
      this.setData({
        jackpotList: res.data.result,
        luckNum: 4
      })
    })
  },
  //抽奖
  todraw(data) {
    console.log(parseInt(data.currentTarget.dataset.num))
    this.setData({
      drawNum: parseInt(data.currentTarget.dataset.num),
      luckNum: 3,
      giftList: []
    })
    this.getdraw()
  },
  //抽奖
  getdraw(data) {
    let _ = this;
    _.setData({
      turn: data.currentTarget.dataset.turn,
    })
    let timestamp = (Date.parse(new Date()) / 1000).toString();
    let arys = {
      roomId: _.data.roomId,
      userId: app.globalData.user_id,
      token: app.globalData.userToken,
      time: timestamp,
      num: data.currentTarget.dataset.turn.toString(),
    };
    let _token = axios.encryption(arys);
    let params = {
      roomId: _.data.roomId,
      userId: app.globalData.user_id,
      token: app.globalData.userToken,
      num: data.currentTarget.dataset.turn.toString(),
      time: timestamp,
      sign: md5.hexMD5(_token),
    };
    axios.axios({
      url: "/lottery/opengift",
      data: params
    }).then((res) => {
      if (res.data.status == 0) {
        _.setData({
          body_index: '6', //爆炸特效
          lottery_num: res.data.result.lottery_num,
          diamond: res.data.result.diamond,
          opengift: res.data.result.list,
          is_close: false,
          process: false,
        })

        Room_cache_image('https://xunyinjiaoyou.oss-cn-qingdao.aliyuncs.com/static/choujiang/bomb.svga', 'bomb').then((myCanvas6) => {
          _.playSvga4(myCanvas6, "#myCanvas6", '1');
        })
      } else {
        _.setData({
          isJackpot: true,
          is_one: '2',
        })
        wx.showToast({
          title: res.data.text,
          icon: 'none',
          duration: 2000 //持续的时间
        })
      }
    })
  },
  swt_navigateBack() {
    wx.navigateBack({
      delta: 1,
    })
  },
  //关闭魔方
  close_box() {
    if (this.data.is_close) {
      this.setData({
        process: false,
        NextBox: false
      })
    } else {
      this.setData({
        body_index: '1',
        process: false,
        is_close: true,
      })
    }
  },
  //最大购买量
  buy_zuida() {
    this.setData({
      number_s: Math.floor(this.data.diamond / 200)
    })
  },
  //购买次数
  buyfreegift() {
    if (this.data.number_s <= 0) {
      return wx.showToast({
        title: "购买数量格式不正确",
        icon: 'none',
        duration: 2000 //持续的时间
      })
    }

    let timestamp = (Date.parse(new Date()) / 1000).toString();
    let arys = {
      userId: app.globalData.user_id,
      token: app.globalData.userToken,
      time: timestamp,
      num: this.data.number_s.toString(),
    };
    let _token = axios.encryption(arys);
    let params = {
      userId: app.globalData.user_id,
      token: app.globalData.userToken,
      num: this.data.number_s.toString(),
      time: timestamp,
      sign: md5.hexMD5(_token),
    };
    axios.axios({
      url: "/lottery/buyfreegift",
      data: params
    }).then((res) => {
      if (res.data.status == 0) {
        console.log(res.data.result);
        this.setData({
          number_s: null,
          lottery_num: res.data.result.lottery_num,
          diamond: res.data.result.diamond_money,
          isJackpot: false,
        })
        wx.showToast({
          title: res.data.text,
          icon: 'none',
          duration: 2000 //持续的时间
        })
      } else {
        wx.showToast({
          title: res.data.text,
          icon: 'none',
          duration: 2000 //持续的时间
        })
      }
    })
  },
  //
  getMsgFromWeb(e) {
    console.log('getMsgFromWeb', e.detail.data)
  },
  onWebLoad(e) {
    console.log('onWebLoad', e)
  },
  onWebError(e) {
    console.error('onWebError', e)
  },
  //轮播图活动
  rotationChart(data) {
    let _ = this;
    wx.setStorageSync('livePlayerList', this.data.livePlayerList)
    let url = data.currentTarget.dataset.url;
    let codetest = RegExp(/http/);
    if (codetest.test(url)) {
      //地址中有http值
      wx.navigateTo({
        url: '../link/link?url=' + data.currentTarget.dataset.url
      })
    } else {
      // this.setData({
      //   EnergyEating: true,
      //   display: 'block',
      // })
      this.energy()
      this.setData({
        features: false,
        NextBox: true,
      })
      // this.playSvga4('https://xunyinjiaoyou.oss-cn-qingdao.aliyuncs.com/static/choujiang/static.svga', "#myCanvas2", '0')
      Room_cache_image('https://xunyinjiaoyou.oss-cn-qingdao.aliyuncs.com/static/choujiang/static.svga', 'static').then((myCanvas2) => {
        _.playSvga4(myCanvas2, "#myCanvas2", '0');
      })
      this.getMyDiamond();
    }
  },
  //获取砖石数和抽奖次数
  getMyDiamond() {
    let timestamp = (Date.parse(new Date()) / 1000).toString();
    let arys = {
      userId: app.globalData.user_id.toString(),
      token: app.globalData.userToken,
      time: timestamp,
    };
    let _token = axios.encryption(arys);
    let params = {
      userId: app.globalData.user_id.toString(),
      token: app.globalData.userToken,
      time: timestamp,
      sign: md5.hexMD5(_token),
    };
    axios.axios({
      url: "/lottery/getMyDiamond",
      data: params
    }).then((res) => {
      if (res.data.status == 0) {
        this.setData({
          diamond: res.data.result.diamond,
          lottery_num: res.data.result.lottery_num,
        })
      } else {
        wx.showToast({
          title: res.data.text,
          icon: 'none',
          duration: 2000 //持续的时间
        })
      }
    })
  },
  buy_zhuan() {
    this.setData({
      NextBox: false,
      is_one: '2',
      isJackpot: true,
    })
  },
  //玩法介绍
  rule_title_text() {
    this.setData({
      is_close: false,
      body_index: "2",
      box_rule: false,
    })
    let timestamp = (Date.parse(new Date()) / 1000).toString();
    let arys = {
      userId: app.globalData.user_id.toString(),
      token: app.globalData.userToken,
      time: timestamp,
    };
    let _token = axios.encryption(arys);
    let params = {
      userId: app.globalData.user_id.toString(),
      token: app.globalData.userToken,
      time: timestamp,
      sign: md5.hexMD5(_token),
    };
    axios.axios({
      url: "/lottery/playdesc",
      data: params
    }).then((res) => {
      if (res.data.status == 0) {
        let arr = res.data.result.split(/[(\r\n)\r\n]+/);
        this.setData({
          text_title_list: arr
        })
        // console.log(this.data.text_title_list);
      }
    })
  },
  upper(e) {
    console.log(e);
    this.awardRecord()
  },
  //获奖记录
  awardRecord() {
    this.setData({
      is_close: false,
      body_index: "3",
      box_rule: false,
    })
    if (!this.data.page_mylog_data) return wx.showToast({
      title: '没有更多数据~~',
      icon: 'none',
      duration: 2000,
    })
    this.data.page_mylog++
    let params = {
      page: this.data.page_mylog,
    };
    axios.axios({
      url: "/lottery/mylog",
      data: params
    }).then((res) => {
      // console.log(res);
      if (res.data.status == 0) {
        if (res.data.result.length > 0) {
          let a = this.data.lucktop;
          let b = res.data.result
          let c = a.concat(b);
          this.setData({
            page_mylog_data: true,
            lucktop: c
          })
        } else {
          this.setData({
            page_mylog_data: false, //
          })
        }
        // console.log(this.data.text_title_list);
      }
    })
  },
  // 关闭奖池
  close_box_ackpot() {
    this.setData({
      isJackpot: false
    })
  },
  //奖池
  Jackpot() {
    this.setData({
      box_rule: false,
      NextBox: false
    })
    let timestamp = (Date.parse(new Date()) / 1000).toString();
    let arys = {
      userId: app.globalData.user_id.toString(),
      token: app.globalData.userToken,
      time: timestamp,
    };
    let _token = axios.encryption(arys);
    let params = {
      userId: app.globalData.user_id.toString(),
      token: app.globalData.userToken,
      time: timestamp,
      sign: md5.hexMD5(_token),
    };
    axios.axios({
      url: "/lottery/boxgiftlist",
      data: params
    }).then((res) => {
      if (res.data.status == 0) {
        this.setData({
          jackpotList: res.data.result,
          isJackpot: true,
          is_one: '1',
        })
        console.log(this.data.jackpotList);
      }
    })
  },
  //返回
  return () {
    this.logout();
    this.leaveChat();
    // wx.switchTab({
    //   url: '/pages/index/index',
    // })
  },
  leaveChat() {
    let params = {
      roomId: this.data.roomId,
      userId: app.globalData.user_id.toString(),
      token: app.globalData.userToken,
      shumeiDeviceId: wx.getStorageSync('shumeiDeviceId')
    };
    axios.axios({
      url: "/chat/leaveChat",
      data: params
    }).then((res) => {
      wx.showToast({
        title: res.data.text,
        icon: 'none',
        duration: 2000 //持续的时间
      })
      wx.navigateBack({
        delta: 1,
      })
    })
  },
  //加入房间
  joinRoom() {
    let that = this;
    let params = {
      roomId: this.data.roomId,
      userId: app.globalData.user_id.toString(),
      token: app.globalData.userToken,
      password: this.data.password ? this.data.password : '',
      shumeiDeviceId: wx.getStorageSync('shumeiDeviceId'),
      clientId: wx.getStorageSync('getClientId')
    };
    axios.axios({
      url: "/chat/joinRoom",
      data: params
    }).then((res) => {
      if (res.data.status == 0) {
        this.setData({
          room_password: false, //密码进入
          roomId: res.data.result.roomInfo.room_id.toString(),
          zogtoken: res.data.result.zegoToken,
          phrase: res.data.result.phrase,
          "list.userlist": res.data.result.userList,
          "list.room_info": res.data.result.roomInfo,
          myUserInfo: res.data.result.myUserInfo
        })
        let list_image_gb_one;

        if (res.data.result.roomInfo.bgType == "svga") {
          list_image_gb_one = 'https://img.xunyinjiaoyou.com/static/xiaochengxu/roombg/' + res.data.result.roomInfo.bgName + '.svga';
        } else {
          list_image_gb_one = 'https://img.xunyinjiaoyou.com/static/xiaochengxu/roombg/' + res.data.result.roomInfo.bgName + '.png';
        }
        Room_cache_image(list_image_gb_one, res.data.result.roomInfo.bgName).then((list_image_gb_one) => {
          console.log(res.data.result.roomInfo.bgType);
          if (res.data.result.roomInfo.bgType == "svga") {
            that.playSvga7(list_image_gb_one, "#myCanvas7", '0') //背景svga
          } else {
            that.setData({
              list_image_gb_one: list_image_gb_one
            })
          }
        })

        if (this.data.myUserInfo.adminType == '1' || this.data.myUserInfo.adminType == '2' || this.data.myUserInfo.adminType == '3') { //是否房间管理员
          this.setData({
            isadministrators: true
          })
        } else {
          this.setData({
            isadministrators: false
          })
        }
        let studentsinfo = [];
        //提取数组的部分元素组成一个新数组
        res.data.result.userList.forEach(item => {
          let newdata = {};
          newdata.user_id = item.user_id;
          studentsinfo.push(newdata);
        });
        wx.setStorageSync('userlist_', JSON.stringify(this.data.userlist_));
        let user_list = wx.getStorageSync('UserInformation')
        this.setData({
          top_list: res.data.result.topList,
          userlist_: studentsinfo,
          ad_list: res.data.result.adList,
        })
        setTimeout(() => {
          this.setData({
            loading: false,
          }) // 在当前同步流程结束后，下一个时间片执行
        }, 1000)

        let item = {
          "charmPic": user_list.charmPic,
          "driver_info": res.data.result.driverInfo[0] ? res.data.result.driverInfo[0].alias_name : '', //座驾
          "driver_name": res.data.result.driverInfo[0] ? res.data.result.driverInfo[0].driver_name : '', //座驾名字
          "effect": res.data.result.enterInfo[0] ? res.data.result.enterInfo[0].alias_name : '', //进场特效
          "fromUserHeadPic": user_list.headPic,
          "isNew": user_list.isNew,
          "level": user_list.levelPic,
          "messageContent": '进入房间',
          "userId": user_list.userId,
          "userName": user_list.nickname,
        }
        this.sendMsg(item, "joinRoom")
        if (this.data.connectType == -1) {
          zg = initSDK(this);
          zg && this.getLoginToken();
          zg && this.acceptMessage();
        }
      } else if (res.data.status == 101) {
        this.setData({
          room_password: true
        })
        wx.showToast({
          title: res.data.text,
          icon: 'none',
          duration: 2000 //持续的时间
        })
      } else {
        wx.showToast({
          title: res.data.text,
          icon: 'none',
          duration: 2000 //持续的时间
        })
        // this.data.client.unsubscribe('xy_room/room' + this.data.roomId)
        var t;
        clearTimeout(t);
        t = setTimeout(function () {
          wx.navigateBack({
            delta: 1
          })
        }, 2000);
      }
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

    this.setData({
      specialEffects: wx.getStorageSync('specialEffects') ? wx.getStorageSync('specialEffects') : false,
      roomId: options.roomId,
      Sum_: app.globalData.Sum_
    })
    this.joinRoom();
    this.userInfo_();
    this.giv_info();
  },

  iponeInput(data) {
    this.setData({
      inputMessage: data.detail.value
    })
  },
  inputFocus(e) {
    if (this.data.inputMessage_ == "聊点什么吧...") {
      this.setData({
        inputMessage: '',
      })
    }
    this.setData({
      isinput_keyboardentry: true,
      input_keyboardentry: e.detail.height - 2
    })
  },
  inputBlur(e) {
    console.log(e);
    if (this.data.inputMessage == "") {
      this.setData({
        issend_: false,
        inputMessage_: '聊点什么吧...',
      })
    } else {
      this.setData({
        issend_: true,
        inputMessage_: this.data.inputMessage,
      })
    }
    this.setData({
      isinput_keyboardentry: false,
      input_keyboardentry: 0,
    })
    console.log("input blur");
  },
  //管理员功能
  authority(data) {
    console.log(data.currentTarget.dataset.authority);
    console.log(data.currentTarget.dataset.authority);
    switch (data.currentTarget.dataset.authority) {
      case '0':
        this.removeWheatSequence(); //移除麦序
        break;
      case '1':
        if (data.currentTarget.dataset.relieve == '0') {
          this.forbiddenWords("1"); //管理员禁言
        } else {
          this.forbiddenWords("2"); //管理员解除禁言
        }
        break;
      case '2':
        this.clearCharm(); //清空魅力值
        break;
      case '3':
        this.delUsers()
        break;
    }
  },
  //管理员移除麦序
  removeWheatSequence() {
    let timestamp = (Date.parse(new Date()) / 1000).toString();
    let arys = {
      roomId: this.data.roomId,
      userId: app.globalData.user_id,
      memberId: this.data.memberId,
      token: app.globalData.userToken,
      time: timestamp,
    };
    let _token = axios.encryption(arys);
    let params = {
      roomId: this.data.roomId,
      userId: app.globalData.user_id,
      memberId: this.data.memberId,
      token: app.globalData.userToken,
      time: timestamp,
      sign: md5.hexMD5(_token),
    };
    axios.axios({
      url: "/chat/delWait",
      data: params
    }).then((res) => {
      wx.showToast({
        title: res.data.text,
        icon: 'none',
        duration: 2000 //持续的时间
      })
      this.setData({
        cardShow: false,
        isguan: false,
      })
    })
  },
  //管理员禁言
  forbiddenWords(type) {
    let timestamp = (Date.parse(new Date()) / 1000).toString();
    let arys = {
      roomId: this.data.roomId,
      userId: app.globalData.user_id,
      memberId: this.data.memberId,
      token: app.globalData.userToken,
      type: type,
      time: timestamp,
    };
    let _token = axios.encryption(arys);
    let params = {
      type: type,
      roomId: this.data.roomId,
      userId: app.globalData.user_id,
      memberId: this.data.memberId,
      token: app.globalData.userToken,
      time: timestamp,
      sign: md5.hexMD5(_token),
    };
    axios.axios({
      url: "/chat/chatMute",
      data: params
    }).then((res) => {
      wx.showToast({
        title: res.data.text,
        icon: 'none',
        duration: 2000 //持续的时间
      })
      this.setData({
        cardShow: false,
        isguan: false,
      })
    })
  },
  //管理员清空魅力值
  clearCharm() {
    let timestamp = (Date.parse(new Date()) / 1000).toString();
    let arys = {
      roomId: this.data.roomId,
      userId: app.globalData.user_id,
      toUserId: this.data.memberId,
      token: app.globalData.userToken,
      time: timestamp,
    };
    let _token = axios.encryption(arys);
    let params = {
      roomId: this.data.roomId,
      userId: app.globalData.user_id,
      toUserId: this.data.memberId,
      token: app.globalData.userToken,
      time: timestamp,
      sign: md5.hexMD5(_token),
    };
    axios.axios({
      url: "/chat/clear_charm",
      data: params
    }).then((res) => {
      this.setData({
        cardShow: false,
        isguan: false,
      })
      wx.showToast({
        title: res.data.text,
        icon: 'none',
        duration: 2000 //持续的时间
      })
    })
  },

  //踢出房间
  delUsers() {
    let timestamp = (Date.parse(new Date()) / 1000).toString();
    let arys = {
      roomId: this.data.roomId,
      userId: app.globalData.user_id,
      memberId: this.data.memberId,
      token: app.globalData.userToken,
      time: timestamp,
    };
    let _token = axios.encryption(arys);
    let params = {
      roomId: this.data.roomId,
      userId: app.globalData.user_id,
      memberId: this.data.memberId,
      token: app.globalData.userToken,
      time: timestamp,
      sign: md5.hexMD5(_token),
    };
    axios.axios({
      url: "/chat/delUsers",
      data: params
    }).then((res) => {
      this.setData({
        cardShow: false,
        isguan: false,
      })
      wx.showToast({
        title: res.data.text,
        icon: 'none',
        duration: 2000 //持续的时间
      })
    })
  },

  async getLoginToken() { //登录房间
    try {
      await zg.logoutRoom();
      const userID = app.globalData.user_id.toString();
      // const channel_name = this.data.channel_name;
      const roomId = this.data.roomId;
      const userName = this.data.user_Info_list.nickname;
      const _token = this.data.zogtoken;
      /** 开始登录房间 */
      let isLogin = await zg.loginRoom(roomId, _token, {
        userID: userID,
        userName: userName
      }, {
        userUpdate: true
      });
      if (isLogin) { //登录成功
        this.setData({
          connectType: 1
        });
      } else {
        console.error('login fail')
      }
    } catch (error) {
      console.error('error: ', error);
    }
  },
  async logout() {
    try {
      if (this.data.livePusherUrl) {
        zg.stopPublishingStream(app.globalData.user_id);
        this.data.livePusher.stop();
        this.setData({
          livePusherUrl: ''
        });
      }
      if (this.data.livePlayerList.length > 0) {
        this.data.livePlayerList.forEach(async (item) => {
          zg.stopPlayingStream(item.streamID);
        });
        this.setData({
          livePlayerList: []
        });
      }
      /** 登出房间 */
      if (zg && this.data.connectType === 1) await zg.logoutRoom(this.data.roomId);
    } catch (error) {
      console.error('error: ', error);
    }

  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    let tim;
    tim = IMSDK(this)
    let messageList_liaot = wx.getStorageSync('messageList_liaot');
    this.setData({
      tim,
      messageList_liaot
    })
    if (this.data.connectType == 0) { //0掉出房间，断开状态
      zg = initSDK(this);
      console.log(zg);
      zg && this.getLoginToken();
      zg && this.acceptMessage();
    }

    // this.energy() //能量池
    var that = this
    app.globalData.callback = function (res) {
      //res  接收websocket onMessage事件返回的数据
      that.initEventHandle(res)
    }
    wx.setNavigationBarColor({
      frontColor: '#ffffff',
      backgroundColor: '#ffffff'
    })
  },
  initEventHandle(message) {
    var that = this;
    let message_ = {};
    message_ = JSON.parse(message.data);
    console.log(message_);
    if (message_.mode == "dev" && axios.testInterface == 'http://testapi2.xunyinjiaoyou.com') {
      let newtime = wx.getStorageSync('newtime')
      let timestamp = Date.parse(new Date());
      let number = message_.createTime - newtime - timestamp;
      if (Math.abs(number) > 20000) {
        return
      }
      if (message_.type == "bigGift") { //全麦礼物
        let result_message = axios.Decrypt(message_.result);
        that.setData({
          WholeWheat: JSON.parse(result_message),
          isWholeWheat: true, //公屏礼物动效
        })
        let timer
        clearTimeout(timer)
        timer = setTimeout(() => { //设置延迟执行
          that.setData({
            isWholeWheat: false, //送礼图片
          })
        }, 8000);
      } else if (message_.type == "sendBarrage") { //魔方大礼物
        console.log(message_.result);
        let result_message = axios.Decrypt(message_.result);
        that.setData({
          isbig_gift: true, //中奖特效
          big_gift_: JSON.parse(result_message), //公屏礼物动效
        })
        let timer
        clearTimeout(timer)
        timer = setTimeout(() => { //设置延迟执行
          that.setData({
            isbig_gift: false, //中奖特效
          })
        }, 8000);
      } else if (message_.type == "updateLevel") { //财富等级升级（大于等级40级）
        let result_message = axios.Decrypt(message_.result);
        that.setData({
          upgrade: JSON.parse(result_message), //
          isupgrade: true, //公屏礼物动效
        })
        let timer
        clearTimeout(timer)
        timer = setTimeout(() => { //设置延迟执行
          that.setData({
            isupgrade: false, //送礼图片
          })
        }, 8000);
      } else if (message_.type == "updateRoomAdmin") {
        let result_message = JSON.parse(axios.Decrypt(message_.result));
        console.log(result_message);
        that.setData({
          "myUserInfo.adminType": result_message.adminType,
        })
        if (this.data.myUserInfo.adminType == '1' || this.data.myUserInfo.adminType == '2' || this.data.myUserInfo.adminType == '3') { //是否房间管理员
          this.setData({
            isadministrators: true
          })
        } else {
          this.setData({
            isadministrators: false
          })
        }
      } else if (message_.type == "removeUser") {
        let result_message = JSON.parse(axios.Decrypt(message_.result));
        console.log(result_message);
        wx.showToast({
          title: result_message.text,
          icon: 'none',
          duration: 2000 //持续的时间
        })
        this.leaveChat()
      } else if (message_.type == "energyJoinNormal") { //普通能量池抽奖
        let result_message = JSON.parse(axios.Decrypt(message_.result));
        if (this.data.EnergyPoolLevel == '1' || this.data.EnergyPoolLevel == '2') {
          this.setData({
            'energy_index.percentage': result_message.percentage
          })
        }
      } else if (message_.type == "energyJoinSuper") { //高能量池抽奖
        let result_message = JSON.parse(axios.Decrypt(message_.result));
        if (this.data.EnergyPoolLevel == '3' || this.data.EnergyPoolLevel == '4') {
          this.setData({
            'energy_index.percentage': result_message.percentage
          })
        }
      } else if (message_.type == "energyOpenNormal") { //普通能量池中奖
        let result_message = JSON.parse(axios.Decrypt(message_.result));
        console.log(result_message);
        let energy = {
          result: result_message,
          type: 'energy'
        }
        this.setData({
          countDown: 3,
          EnergyPoolLevel: '2',
          energyOpenNormal: result_message,
          messageList: [...this.data.messageList, energy],
        })
        var t;
        t = setInterval(() => {
          if (this.data.countDown == 0) {
            this.tab_qiehuang()
            return clearInterval(t)
          }
          this.data.countDown--
          this.setData({
            countDown: this.data.countDown--
          })
        }, 1000)
      } else if (message_.type == "energyOpenSuper") { //高能量池中奖
        let result_message = JSON.parse(axios.Decrypt(message_.result));
        console.log(result_message);
        let energy = {
          result: result_message,
          type: 'energy'
        }
        this.setData({
          countDown: 3,
          EnergyPoolLevel: '4',
          energyOpenNormal: result_message,
          messageList: [...this.data.messageList, energy],
        })
        var t;
        t = setInterval(() => {
          if (this.data.countDown == 0) {
            this.tab_qiehuang()
            return clearInterval(t)
          }
          this.data.countDown--
          this.setData({
            countDown: this.data.countDown--
          })
        }, 1000)
      } else if (message_.type == "doingGift") { //高能量池中奖
        let result_message = JSON.parse(axios.Decrypt(message_.result));
        if (this.data.points.length > 0) {
          // var geyao1 = this.data.points.some((item,index) => {
          //     return item.giftId == result_message.giftId
          // })
          // let result =  this.data.points.find((item,index) => item.user_id == user_id.result.userId)
          // return result.position
          // console.log(geyao1); 
          // if (geyao1) {
          //   this.setData({  
          //     points: arr,
          //   })
          // }else{

          // }
          // this.data.points.some((value, index, arr) => {
          //   if(value.giftId == result_message.giftId){ 
          //     console.log('同:', result_message.giftNum);
          //     arr[index] = result_message;
          //     this.setData({
          //       points:arr,
          //     })
          //   }else{
          //     console.log('异:', result_message.giftNum);
          //     this.setData({
          //       points:[...this.data.points,result_message]
          //     })
          //   }
          // });
        } else {
          this.data.points.push(result_message)
        }
      }
    } else if (message_.mode == "product" && axios.testInterface == 'https://api2.xunyinjiaoyou.com') {
      let newtime = wx.getStorageSync('newtime')
      let timestamp = Date.parse(new Date());
      let number = message_.createTime - newtime - timestamp;
      if (Math.abs(number) > 20000) {
        return
      }
      if (message_.type == "bigGift") { //全麦礼物
        let result_message = axios.Decrypt(message_.result);
        that.setData({
          WholeWheat: JSON.parse(result_message),
          isWholeWheat: true, //公屏礼物动效
        })
        let timer
        clearTimeout(timer)
        timer = setTimeout(() => { //设置延迟执行
          that.setData({
            isWholeWheat: false, //送礼图片
          })
        }, 8000);
      } else if (message_.type == "sendBarrage") { //魔方大礼物
        console.log(message_.result);
        let result_message = axios.Decrypt(message_.result);
        that.setData({
          isbig_gift: true, //中奖特效
          big_gift_: JSON.parse(result_message), //公屏礼物动效
        })
        let timer
        clearTimeout(timer)
        timer = setTimeout(() => { //设置延迟执行
          that.setData({
            isbig_gift: false, //中奖特效
          })
        }, 8000);
      } else if (message_.type == "updateLevel") { //财富等级升级（大于等级40级）
        let result_message = axios.Decrypt(message_.result);
        that.setData({
          upgrade: JSON.parse(result_message), //
          isupgrade: true, //公屏礼物动效
        })
        let timer
        clearTimeout(timer)
        timer = setTimeout(() => { //设置延迟执行
          that.setData({
            isupgrade: false, //送礼图片
          })
        }, 8000);
      } else if (message_.type == "updateRoomAdmin") {
        let result_message = JSON.parse(axios.Decrypt(message_.result));
        console.log(result_message);
        that.setData({
          "myUserInfo.adminType": result_message.adminType,
        })
        if (this.data.myUserInfo.adminType == '1' || this.data.myUserInfo.adminType == '2' || this.data.myUserInfo.adminType == '3') { //是否房间管理员
          this.setData({
            isadministrators: true
          })
        } else {
          this.setData({
            isadministrators: false
          })
        }
      } else if (message_.type == "removeUser") {
        let result_message = JSON.parse(axios.Decrypt(message_.result));
        console.log(result_message);
        this.leaveChat()
        wx.showToast({
          title: result_message.text,
          icon: 'none',
          duration: 2000 //持续的时间
        })
      } else if (message_.type == "energyJoinNormal") { //普通能量池抽奖
        let result_message = JSON.parse(axios.Decrypt(message_.result));
        if (this.data.EnergyPoolLevel == '1' || this.data.EnergyPoolLevel == '2') {
          this.setData({
            'energy_index.percentage': result_message.percentage
          })
        }
      } else if (message_.type == "energyJoinSuper") { //高能量池抽奖
        let result_message = JSON.parse(axios.Decrypt(message_.result));
        console.log(result_message);
        if (this.data.EnergyPoolLevel == '3' || this.data.EnergyPoolLevel == '4') {
          this.setData({
            'energy_index.percentage': result_message.percentage
          })
        }
      } else if (message_.type == "energyOpenNormal") { //普通能量池中奖
        let result_message = JSON.parse(axios.Decrypt(message_.result));
        console.log(result_message);
        let energy = {
          result: result_message,
          type: 'energy'
        }
        this.setData({
          countDown: 3,
          EnergyPoolLevel: '2',
          energyOpenNormal: result_message,
          messageList: [...this.data.messageList, energy],
        })
        var t;
        t = setInterval(() => {
          if (this.data.countDown == 0) {
            this.tab_qiehuang()
            return clearInterval(t)
          }
          this.data.countDown--
          this.setData({
            countDown: this.data.countDown--
          })
        }, 1000)
      } else if (message_.type == "energyOpenSuper") { //高能量池中奖
        let result_message = JSON.parse(axios.Decrypt(message_.result));
        console.log(result_message);
        let energy = {
          result: result_message,
          type: 'energy'
        }
        this.setData({
          countDown: 3,
          EnergyPoolLevel: '4',
          energyOpenNormal: result_message,
          messageList: [...this.data.messageList, energy],
        })
        var t;
        t = setInterval(() => {
          if (this.data.countDown == 0) {
            this.tab_qiehuang()
            return clearInterval(t)
          }
          this.data.countDown--
          this.setData({
            countDown: this.data.countDown--
          })
        }, 1000)
      }
    }
    //给服务端发送joinRoom消息
    let heartCheck = {
      timeout: 5000,
      timeoutObj: null,
      serverTimeoutObj: null,
      reset: function () {
        clearTimeout(this.timeoutObj);
        clearTimeout(this.serverTimeoutObj);
        return this;
      },
      start: function () {
        this.timeoutObj = setTimeout(() => {
          let obj;
          obj = {
            type: "joinRoom",
            roomId: that.data.roomId,
          }
          let objToStr = JSON.stringify(obj)
          wx.sendSocketMessage({
            data: objToStr,
            success() {
              console.log("发送joinRoom成功", objToStr);
            },
          });
        }, this.timeout);
      }
    };
    heartCheck.reset().start()
  },

  onReady() {},

  //统一接收,处理服务端消息
  acceptMessage() {
    // 用户状态更新回调
    let that = this
    zg.on('IMRecvBroadcastMessage', (roomID, chatData) => {
      let IMinformation = JSON.parse(chatData[0].message);
      // console.log('Zg即时通讯', IMinformation);
      if (IMinformation.type == "chatroomFace") { //上麦表情及骰子
        let position = axios.isuser_id(that.data.list.userlist, JSON.parse(chatData[0].message))
        this.setData({
          isemoticon: position,
          messageList_: JSON.parse(chatData[0].message),
        })
        if (JSON.parse(chatData[0].message).result.path == "maixu") {
          let timer
          clearTimeout(timer)
          timer = setTimeout(() => { //设置延迟执行
            this.setData({
              maixu: true,
              maixu_image: 'https://img.xunyinjiaoyou.com/static/face/maixu/ic_mx_' + JSON.parse(chatData[0].message).result.number + '.png',
            })
            let timer2
            clearTimeout(timer2)
            timer2 = setTimeout(() => { //设置延迟执行 
              this.setData({
                isemoticon: null,
                maixu: false,
                messageList: [...this.data.messageList, JSON.parse(chatData[0].message)],
              })
            }, 3000);
          }, 3500);
        } else {
          let timer
          clearTimeout(timer)
          timer = setTimeout(() => { //设置延迟执行
            this.setData({
              isemoticon: null,
            })
          }, 3000)
        }
      } else if (IMinformation.type == "gift") { //接收礼物特效
        let message = JSON.parse(chatData[0].message);
        // if (message.result.giftInfo.giftType != '3') { //不是幸运礼物
        let codesvga = RegExp(/.svga/);
        let codemp4 = RegExp(/.mp4/);
        console.log(message);
        if (message.result.giftInfo.giftType == "4") { //辛运礼物
          if (this.data.isMp4_video || this.data.luckbox_) {
            this.setData({
              messageList: [...this.data.messageList, message],
              luckGiftUrl: [...this.data.luckGiftUrl, message],
            })
          } else {
            this.setData({
              voide_mp4: message.result.giftInfo.luckGiftUrl,
              isMp4_video: true,
              messageList: [...this.data.messageList, message],
              luckGiftUrl: [...this.data.luckGiftUrl, message],
            })
          }
        } else if (codemp4.test(message.result.giftInfo.imageFile)) { //礼物是mp4格式
          this.setData({
            voide_mp4: message.result.giftInfo.imageFile,
            isMp4_video: true,
            messageList: [...this.data.messageList, message],
          })
        } else if (codesvga.test(message.result.giftInfo.imageFile)) { //礼物是svga格式
          this.setData({
            approachAnimation: true, //特效
            messageList: [...this.data.messageList, message],
          })
          this.playSvga4(message.result.giftInfo.imageFile, "#myCanvas3", message.result.receivers.length * message.result.giftInfo.sendGiftNum)
        } else { //礼物没有特效
          this.setData({
            giftInfo: JSON.parse(chatData[0].message).result,
            messageList: [...this.data.messageList, message],
            receiversArr: message.result.receivers,
            gift_imgicon_wu: message.result.giftInfo.icon,
            gift_nowar_: true, //送礼图片
            gift_nowar: true,
          })
          let timer
          clearTimeout(timer)
          timer = setTimeout(() => { //设置延迟执行
            message.result.receivers.forEach(item => {
              if (item.position == 0) {
                item.position_top = -30
                item.position_left = 4
              } else if (item.position < 5) {
                item.position_top = -16
                item.position_left = item.position * 24 - 56
              } else {
                item.position_top = -4
                item.position_left = (item.position - 4) * 24 - 56
              }
            })
            this.setData({
              receiversArr: message.result.receivers,
              position_width: 30,
              position_height: 30,
            })
          }, 1000);
          let timers
          clearTimeout(timers)
          timers = setTimeout(() => { //设置延迟执行
            this.setData({
              position_width: 100,
              position_height: 100,
              gift_imgicon_wu: '',
              gift_nowar_: false, //送礼图片
            })
          }, 4000);
        }
        // }
      } else if (IMinformation.type == "cleanscreen") { //清除公屏
        wx.showToast({
          title: JSON.parse(chatData[0].message).result.text,
          icon: 'none',
          duration: 2000 //持续的时间
        })
        that.setData({
          messageList: []
        })
      } else if (IMinformation.type == "joinRoom") { //他人进入房间
        if (JSON.parse(chatData[0].message).result.driver_info) { //座驾
          this.setData({
            approachAnimation: true, //进场特效
          })
          this.playSvga4(JSON.parse(chatData[0].message).result.driver_info, "#myCanvas3", '1')
        }
        if (JSON.parse(chatData[0].message).result.effect) { //进场动画
          // this.setData({
          //   joinRoom_s: true,
          // })
          this.getIntoQueue_Svge5(JSON.parse(chatData[0].message))
        }

        this.setData({
          messageList: [...this.data.messageList, JSON.parse(chatData[0].message)],
        })
      } else if (IMinformation.type == "update_wait") { //麦序更新
        // console.log(chatData[0].message);
        let arr = JSON.parse(chatData[0].message).result
        let codetest = RegExp(/http/);
        var newArr = arr.map(item => ({
          charm: item.charm,
          nickname: item.name,
          position: item.p,
          head_pic: codetest.test(item.pic) ? item.pic : (item.pic ? that.data.img_header + item.pic : ""),
          head_avatar: codetest.test(item.pic2) ? item.pic2 : (item.pic2 ? that.data.img_header + item.pic2 : ""),
          sex: item.sex,
          status: item.status,
          user_id: item.uid,
        }))
        // console.log(newArr);
        this.data.list.userlist[newArr[0].position] = newArr[0]
        newArr.length > '1' ? this.data.list.userlist[newArr[1].position] = newArr[1] : ''
        that.setData({
          "list.userlist": that.data.list.userlist
        })
        let studentsinfo = [];
        //提取数组的部分元素组成一个新数组
        that.data.list.userlist.forEach(item => {
          let newdata = {};
          newdata.user_id = item.user_id;
          studentsinfo.push(newdata);
        });
        that.setData({
          userlist_: studentsinfo,
        })
        // that.user_list()
        wx.setStorageSync('userlist_', JSON.stringify(that.data.userlist_));
        if (that.data.livePlayerList.length > '0') {
          var position;
          that.data.list.userlist.forEach(function (item) {
            if (item.user_id.toString() == that.data.livePlayerList[0].streamID) {
              position = item.position
            }
          })
          that.setData({
            position_mk: position
          })
        } else {
          that.setData({
            position_mk: null
          })
        }
      } else if (IMinformation.type == "updateLevel") { //财富等级升级（大于等级40级）
        this.setData({
          upgrade: message.result, //
          isupgrade: true, //公屏礼物动效
        })
        let timer
        clearTimeout(timer)
        timer = setTimeout(() => { //设置延迟执行
          that.setData({
            isupgrade: false, //送礼图片
          })
        }, 8000);
      } else if (IMinformation.type == "text") { //房间公聊文本
        that.setData({
          messageList: [...this.data.messageList, JSON.parse(chatData[0].message)],
        });
      } else if (IMinformation.type == "updateRoomInfo") { //房间信息更改
        that.setData({
          "list.room_info": JSON.parse(chatData[0].message).result
        });
      } else {
        that.setData({
          messageList: [...this.data.messageList, JSON.parse(chatData[0].message)],
        });
      }
      that.scrollTop_length_2(); //聊天框自动下拉
    });
  },
  scrollTop_length_2() { //消息自动下拉接收消息
    const query = wx.createSelectorQuery()
    query.select('#room_chat_list').scrollOffset()
    query.exec((res) => {
      if (res[0]) {
        if (res[0].scrollHeight - res[0].scrollTop > 500) {
          this.setData({
            is_new_infor: true
          })
        } else {
          this.setData({
            scrollTop: res[0].scrollHeight
          })
        }
      }
    })
  },
  scrollTop_length() { //消息自动下拉接收消息
    const query = wx.createSelectorQuery()
    query.select('#room_chat_list').scrollOffset()
    query.exec((res) => {
      this.setData({
        is_new_infor: false,
        scrollTop: res[0].scrollHeight
      })
    })
  },
  //滚动
  bindscroll(event) {
    let scroolbottom = event.detail.scrollHeight - event.detail.scrollTop;
    // console.log(scroolbottom);
    if (scroolbottom < 400) {
      this.setData({
        is_new_infor: false,
      })
    }
  },

  bindscrolltolower() {
    if (!this.data.page_show) {
      this.data.page++
      this.setData({
        page: this.data.page
      })
      this.luckToppage()
    } else {
      wx.showToast({
        title: '没有更多数据！！！',
        icon: 'none',
        duration: 1000 //持续的时间
      })
    }
  },
  //点击更多信息
  bottomscroll() {
    const query = wx.createSelectorQuery()
    query.select('#room_chat_list').scrollOffset()
    query.exec((res) => {
      this.setData({
        is_new_infor: false,
        scrollTop: res[0].scrollHeight
      })
    })
  },
  //重新连接后更新麦位
  waitList() {
    let params = {
      roomId: this.data.roomId,
      userId: app.globalData.user_id,
      token: app.globalData.userToken,
    };
    axios.axios({
      url: "/chat/waitList",
      data: params
    }).then((res) => {
      if (res.data.status == 0) {
        this.setData({
          'list.userlist': res.data.result
        })
      } else {
        wx.showToast({
          title: res.data.text,
          icon: 'none',
          duration: 2000 //持续的时间
        })
      }

    })
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    // this.logout();
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    if (this.data.iswebview) {
      return wx.navigateTo({
        url: '/pages/room/room?roomId=' + this.data.roomId + '&password=' + this.data.password,
      })
    }
    this.logout();
    if (axios.isgetStorageSync("userlist_", app.globalData.user_id)) { //我在麦上，下麦
      this.leaveWait()
    } else { //没在麦上，也下麦
      this.leaveWait()
    }
    clearTimeout(this.timeoutObj)
  },
  phrase() {
    this.setData({ 
      phrase: false
    })
  },
  //下麦
  leaveWait() {
    let timestamp = (Date.parse(new Date()) / 1000).toString();
    let arys = {
      roomId: this.data.roomId,
      userId: app.globalData.user_id,
      token: app.globalData.userToken,
      time: timestamp,
    };
    let _token = axios.encryption(arys);
    let params = {
      roomId: this.data.roomId,
      userId: app.globalData.user_id,
      token: app.globalData.userToken,
      time: timestamp,
      sign: md5.hexMD5(_token),
    };
    axios.axios({
      url: "/chat/leaveWait",
      data: params
    }).then((res) => {
      this.setData({
        cardShow: false,
        microPhone: false
      })
    })
  },

  userInfo_() {
    let params = {
      userId: app.globalData.user_id,
      token: app.globalData.userToken,
    };
    axios.axios({
      url: "/user/userInfo",
      data: params
    }).then((res) => {
      // console.log(res.data.result),
      this.setData({
        user_Info_list: res.data.result.user,
        diamond: res.data.result.user.diamondMoney,
      })
    })
  },
  onFocus: function (e) {
    var that = this;
    that.setData({
      isFocus: true
    });
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },

})
